<?php

namespace app\index\controller;

use app\index\model\AchieveListModel;
use app\index\model\AchieveModel;
use app\index\model\ArchiveTongModel;
use app\index\model\BidModel;
use app\index\model\CertBorrowListModel;
use app\index\model\CertBorrowModel;
use app\index\model\CertCompanyModel;
use app\index\model\CertDownListModel;
use app\index\model\CertDownModel;
use app\index\model\CertEmployFeeModel;
use app\index\model\CertEmployModel;
use app\index\model\CertFormModel;
use app\index\model\CertModel;
use app\index\model\CertPersonModel;
use app\index\model\CertUseBidListModel;
use app\index\model\CertUseBidModel;
use app\index\model\CertUseListModel;
use app\index\model\CertUseModel;
use app\index\model\DeptModel;
use app\index\model\EnginModel;
use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowClassModel;
use app\index\model\FlowLogModel;
use app\index\model\OptionModel;
use app\index\model\UserGangModel;
use app\index\model\UserModel;
use app\index\service\BidService;
use app\index\service\CertService;
use app\index\service\ContractService;
use app\index\service\EnginService;
use app\index\service\FlowService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use app\index\validate\CertBorrow;
use app\index\validate\CertEmploy;
use app\index\validate\CertUse;
use think\Db;
use think\db\Expression;
use think\Request;

class Cert extends Common
{
    public function list_cert_person(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['p.deleted_user','=','0'];
        $where[] = ['p.comid','=',$this->userinfo['comid']];

        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['p.chanid','in', (new MenuService())->get_chanid_sons($param['chanid'])];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['p.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['idcard']) && !empty($param['idcard'])){
            $where[] = ['p.idcard','like', '%'.$param['idcard'].'%'];
        }
        if(isset($param['sex']) && !empty($param['sex'])){
            $where[] = ['p.sex','=', $param['sex']];
        }
        if(isset($param['tel']) && !empty($param['tel'])){
            $where[] = ['p.tel','like', '%'.$param['tel'].'%'];
        }
        if(isset($param['nature']) && !empty($param['nature'])){
            $where[] = ['p.nature','=',$param['nature']];
        }
        if(isset($param['intodt']) && !empty($param['intodt'])){
            $where[] = ['p.intodt','between', explode(' - ', $param['intodt'])];
        }
        if(isset($param['social']) && !empty($param['social'])){
            $where[] = ['p.social','=', $param['social']];
        }
        if(isset($param['socialareas']) && !empty($param['socialareas'])){
            $where[] = ['p.socialareas','like', '%'.$param['socialareas'].'%'];
        }
        if(isset($param['socstartdt']) && !empty($param['socstartdt'])){
            $where[] = ['p.socstartdt','between', explode(' - ', $param['socstartdt'])];
        }
        if(isset($param['outdt']) && !empty($param['outdt'])){
            $where[] = ['p.outdt','between', explode(' - ', $param['outdt'])];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['p.state','=', $param['state']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['is_nature'] = isset($param['nature']) ? $param['nature'] : '';

        $data['social'] = (new OptService())->get_base_info('person_social');
        $data['is_social'] = isset($param['social']) ? $param['social'] : '';

        $data['statueuse'] = (new CertService())->get_cert_person_statueuse();
        $data['is_statueuse'] = isset($param['statueuse']) ? $param['statueuse'] : '';


        $missWhereName = $param['state'] == '离职' ? 'cert_person_leave' : 'cert_person';


        $data['data'] = CertPersonModel::alias('p')
            ->field('p.*,u.realname as userid_name')
            ->leftjoin('user u','u.id=p.userid')
            ->where($where)
            ->where((new MenuService())->get_miss_where($missWhereName, 'p'))
            ->order('p.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['deptid_name'] = DeptModel::get_name_by_pk($item['deptid']);
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['age'] = (new CertService())->get_age_by_idcard($item['idcard']);
                $item['statueuse_name'] = (new CertService())->get_cert_person_statueuse_name($item['statueuse']);
                $item['cert_num'] = CertModel::where(['personid'=>$item['id'],'deleted_user'=>0])->count();
                $item['social_name'] = (new OptService())->get_base_showname('person_social',$item['social']);
                $item['files'] = FileModel::where(['comid'=>$this->userinfo['comid'],'table'=>'cert_person','mid'=>$item['id']])->count();
                $item['xueli_name'] = (new OptService())->get_base_showname('person_xueli',$item['xueli']);
                $item['nature_name'] = (new OptService())->get_base_showname('person_nature',$item['nature']);
                $item['socnum'] = (new CertService())->get_cert_person_social_month($item['socstartdt'],$item['socstartdt']);
                $item['gangid_name'] = UserGangModel::get_name_by_ids($item['gangid'],' / ');
                return $item;
            })->toArray();

        if($param['state'] == '离职'){
            $data['butauth'] = (new MenuService())->get_butauth('cert_person_leave');
        }else{
            $data['butauth'] = (new MenuService())->get_butauth('cert_person');
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_cert_person(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入人员姓名');
            }
            if((new CertService())->check_cert_person_name($param['name'])){
                return outputJson(4000, '人员姓名已存在');
            }
            if(!(new CertService())->check_person_idcard_mate($param['idcard'])){
                return outputJson(4000, '人员身份证号码错误');
            }
            if((new CertService())->check_person_idcard_exist($param['idcard'])){
                return outputJson(4000, '人员身份证号码已存在');
            }
            if(empty($param['nature'])){
                return outputJson(4000, '请选择人员性质');
            }
            if(empty($param['deptid'])){
                return outputJson(4000, '请选择所在部门');
            }
            if(empty($param['social'])){
                return outputJson(4000, '请选择社保状态');
            }


            if($param['userid']){
                $exist = CertPersonModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'userid'=>$param['userid']])->find();
                if($exist){
                    return outputJson(4000, '该用户已被关联，请重新选择');
                }
            }



            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['chanid'] = (new UserService())->get_user_chanid($param['deptid']);
            $param['sex'] = check_sex_by_idcard($param['idcard']);
            $param['birdt'] = check_birdt_by_idcard($param['idcard']);

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $personid = CertPersonModel::insertGetId($param);
                (new OptService())->relation_file($files,'cert_person',$personid);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert_person', $personid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert_person', $personid, '人员');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                halt($e);
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            $data['xueli'] = (new OptService())->get_base_info('person_xueli');
            $data['nature'] = (new OptService())->get_base_info('person_nature');
            $data['social'] = (new OptService())->get_base_info('person_social');
            $data['areas'] = (new OptService())->get_city_cader();
            $data['gangArr'] = (new UserService())->get_usergang_all();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_cert_person(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入人员姓名');
            }
            if((new CertService())->check_cert_person_name($param['name'], $param['id'])){
                return outputJson(4000, '人员姓名已存在');
            }
            if(!(new CertService())->check_person_idcard_mate($param['idcard'])){
                return outputJson(4000, '人员身份证号码错误');
            }
            if((new CertService())->check_person_idcard_exist($param['idcard'], $param['id'])){
                return outputJson(4000, '人员身份证号码已存在');
            }
            if(empty($param['nature'])){
                return outputJson(4000, '请选择人员性质');
            }
            if(empty($param['deptid'])){
                return outputJson(4000, '请选择所在部门');
            }
            if(empty($param['social'])){
                return outputJson(4000, '请选择社保状态');
            }

            if($param['userid']){
                $exist = CertPersonModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'userid'=>$param['userid']])
                    ->where('id','neq', $param['id'])->find();
                if($exist){
                    return outputJson(4000, '该用户已被关联，请重新选择');
                }
            }


            $param['chanid'] = (new UserService())->get_user_chanid($param['deptid']);
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $param['sex'] = check_sex_by_idcard($param['idcard']);
            $param['birdt'] = check_birdt_by_idcard($param['idcard']);
            Db::startTrans();
            try {
                CertPersonModel::update($param);
                CertModel::where(['personid'=>$param['id']])->update(['chanid'=>$param['chanid']]);
                (new OptService())->relation_file($files,'cert_person',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'cert_person', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'cert_person', $param['id'], '人员');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = CertPersonModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000,lang('code_4000'));
            }
            $data['data']['gangid'] = explode(',', $data['data']['gangid']);
            $data['data']['deptid_info'] = (new UserService())->get_users_part_arr($data['data']['deptid'], 'dept');
            $data['data']['userid_info'] = (new UserService())->get_users_part_arr($data['data']['userid'], 'user');

            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            $data['xueli'] = (new OptService())->get_base_info('person_xueli');
            $data['nature'] = (new OptService())->get_base_info('person_nature');
            $data['social'] = (new OptService())->get_base_info('person_social');
            $data['areas'] = (new OptService())->get_city_cader();
            $data['gangArr'] = (new UserService())->get_usergang_all();
            $data['files'] = (new OptService())->get_file('cert_person', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function editsocial_cert_person(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['social'])){
                return outputJson(4000, '请选择社保状态');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                CertPersonModel::update($param);
                (new OptService())->add_flow_log('编辑社保', 'cert_person', $param['id']);
                (new OptService())->add_log_list('编辑社保', 'cert_person', $param['id'], '人员');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = CertPersonModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000,lang('code_4000'));
            }
            $data['social'] = (new OptService())->get_base_info('person_social');
            $data['areas'] = (new OptService())->get_city_cader();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function editout_cert_person(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(!empty($param['outdt'])){
                if($param['outdt'] > date("Y-m-d")){
                    return outputJson(4000, '离职日期不能大于当前日期');
                }
            }

            $cert_list = array_filter($param['cert_list']);
            unset($param['cert_list']);

            $employ_list = array_filter($param['employ_list']);
            unset($param['employ_list']);

            $archive_list = array_filter($param['archive_list']);
            unset($param['archive_list']);

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                CertPersonModel::update($param);

                if(count($cert_list)){
                    foreach ($cert_list as $item){
                        if($item['state'] != 2 && $item['state'] != 3){
                            $item['out_dt'] = '';
                        }
                        CertModel::where(['id'=>$item['id']])->update(['out_dt'=>$item['out_dt'],'state'=>$item['state']]);
                    }
                }

                if(count($employ_list)){
                    foreach ($employ_list as $item){
                        CertEmployModel::where('id',$item['id'])->update(['end_dt'=>$item['end_dt']]);
                        $employ = CertEmployModel::where('id',$item['id'])->find();
                        $this->generate_cert_employ_money($employ['id'],$employ['pay_type'],$employ['personid'],$employ['start_dt'],$employ['end_dt'],$employ['money'],0);
                    }
                }

                if(count($archive_list)){
                    foreach ($archive_list as $item){
                        ArchiveTongModel::where('id',$item['id'])->update(['zhongdt'=>$item['zhongdt']]);
                    }
                }

                (new OptService())->add_flow_log('离职', 'cert_person', $param['id']);
                (new OptService())->add_log_list('离职', 'cert_person', $param['id'], '人员');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                halt($e);
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = CertPersonModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000,lang('code_4000'));
            }

            $cert_data = CertModel::where(['personid'=>$id,'deleted_user'=>0,'comid'=>$this->userinfo['comid']])->select()->toArray();
            $cert_state = (new CertService())->get_cert_state();
            $statueuse = (new CertService())->get_cert_statueuse();
            $goes = (new CertService())->get_cert_goes();
            foreach ($cert_data as &$item){
                $item['major'] = str_replace('[]',' / ',$item['major']);
                $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($item['statueuse']);
                $item['goes_name'] = isset($goes[$item['goes']]) ? $goes[$item['goes']] : '';
            }
            $data['cert_data'] = $cert_data;

            $data['social'] = (new OptService())->get_base_info('person_social');
            $data['cert_state'] = $cert_state;

            // 聘费合同
            $where_em = Db::raw("end_dt = '' or end_dt = '0000-00-00' or end_dt > ".date('Y-m-d'));
            $data['cert_employ'] = CertEmployModel::where(['deleted_user'=>0,'personid'=>$id])
                ->where($where_em)->select()->toArray();

            // 劳动合同
            $where_ar = Db::raw("xianzhidt = '' or xianzhidt = '0000-00-00' or xianzhidt > ".date('Y-m-d'));
            $data['archive_tong'] = ArchiveTongModel::where(['deleted_user'=>0,'arcid'=>$id])
                ->where($where_ar)->select()->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_cert_person(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = CertPersonModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }
        $data['data']['userid_name'] = UserModel::get_realname_by_pk($data['data']['userid']);
        $data['data']['deptid_name'] = DeptModel::get_name_by_pk($data['data']['deptid']);
        $data['data']['gangid_name'] = UserGangModel::get_name_by_ids($data['data']['gangid'],' / ');
        $data['data']['nature'] = (new OptService())->get_base_showname('person_nature',$data['data']['nature']);
        $data['data']['social'] = (new OptService())->get_base_showname('person_social',$data['data']['social']);
        $data['data']['xueli'] = (new OptService())->get_base_showname('person_xueli',$data['data']['xueli']);

        $data['data']['chanid_name'] = DeptModel::get_name_by_pk($data['data']['chanid']);
        $data['data']['age'] = (new CertService())->get_age_by_idcard($data['data']['idcard']);
        $data['files'] = (new OptService())->get_file('cert_person', $data['data']['id']);


        $cert_list = CertModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'personid'=>$data['data']['id']])->select()->toArray();
        foreach ($cert_list as &$item){
            $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);
            $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
            $item['state_name'] = (new CertService())->get_cert_state_name($item['state']);
            $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($item['statueuse']);

            $major = array_filter(explode('[]',$item['major']));
            $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';
            $expiry_dtArr = explode('[]',$item['expiry_dt']);
            $arr = [];
            foreach($expiry_dtArr as $v){
                if(empty($v)){
                    $arr[] = $v;
                }else{
                    if($v < date('Y-m-d')){
                        $arr[] = '<span style="color:red;">'.$v.'</span>';
                    }else{
                        $arr[] = $v;
                    }
                }
            }
            $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';
        }
        $data['cert_list'] = $cert_list;



        $use_list = [];
        $biduse = CertUseBidListModel::alias('list')
            ->field('use.bidid,list.*')
            ->leftJoin('cert_use_bid use', 'use.id = list.useid')
            ->leftJoin('cert cert', 'cert.id = list.certid')
            ->leftJoin('cert_person person', 'person.id = cert.personid')
            ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
            ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1])
            ->where(['person.id'=>$data['data']['id']])
            ->select()->toArray();

        foreach ($biduse as $item){
            $engininfo = BidModel::where(['id'=>$item['bidid']])->find();
            $item['enginid_name'] = $engininfo['name'];
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($engininfo['chanid']);
            $item['engin_state'] = (new EnginService())->get_engin_state_name_tag($engininfo['id'],$engininfo['state']);
            $item['business_name'] = $engininfo['business'] == 1 ? '自营' : '联营';
            $use_list[] = $item;
        }

        $enginuse = CertUseListModel::alias('list')
            ->field('use.enginid,list.*')
            ->leftJoin('cert_use use', 'use.id = list.useid')
            ->leftJoin('cert cert', 'cert.id = list.certid')
            ->leftJoin('cert_person person', 'person.id = cert.personid')
            ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
            ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1])
            ->where(['person.id'=>$data['data']['id']])
            ->select()->toArray();
        foreach ($enginuse as $item){
            $engininfo = EnginModel::where(['id'=>$item['enginid']])->find();
            $item['enginid_name'] = $engininfo['name'];
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($engininfo['chanid']);
            $item['engin_state'] = (new EnginService())->get_engin_state_name_tag($engininfo['id'],$engininfo['state']);
            $item['business_name'] = $engininfo['business'] == 1 ? '自营' : '联营';
            $use_list[] = $item;
        }
        $data['use_list'] = $use_list;



        $data['achieve_list'] = [];


        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_cert_person(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的人员');
        }

        $data = CertPersonModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertpersonModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertpersonModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_person', $data['id'], '人员');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function list_person_dao(Request $request){
        $param = $request->post();
        get_page($param);
        $where[] = ['e.deleted_user','=', 0];
        $where[] = ['e.comid','=',$this->userinfo['comid']];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.name','like', '%'.$param['keyword'].'%'];
        }

        $exp = new Expression('convert(e.name using gbk) asc');
        $data = CertPersonModel::alias('e')
            ->field('e.id,e.name as title')
            ->where($where)
            ->order($exp)
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_cert(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];

        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['expiry_dt']) && !empty($param['expiry_dt'])){
            $expiry_dt = explode(' - ', $param['expiry_dt']);
            $ids = [];
            $c_data = CertModel::where(['deleted_user'=>0])->field('id,expiry_dt')->select();
            foreach ($c_data as $item){
                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                if($expiry_dtArr){
                    foreach ($expiry_dtArr as $dt){
                        if($dt >= $expiry_dt[0] && $dt <= $expiry_dt[1]){
                            $ids[] = $item['id'];
                        }
                    }
                }
            }
            $ids = array_unique($ids);
            $where[] = ['cert.id','in',$ids];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['cert.state','in', $param['state']];
        }
        if(isset($param['electron_dt']) && !empty($param['electron_dt'])){
            $where[] = ['cert.electron_dt','between', explode(' - ', $param['electron_dt'])];

        }
        if(isset($param['inspect_dt']) && !empty($param['inspect_dt'])){
            $where[] = ['cert.inspect_dt','between', explode(' - ', $param['inspect_dt'])];
        }
        if(isset($param['custodianid']) && !empty($param['custodianid'])){
            $where[] = ['u.realname','like', '%'.$param['custodianid'].'%'];
        }
        if(isset($param['store_addr']) && !empty($param['store_addr'])){
            $where[] = ['cert.store_addr','eq', $param['store_addr']];
        }

        if(isset($param['statueuse']) && !empty($param['statueuse'])){
            $where[] = ['cert.statueuse','=', $param['statueuse']];
        }
        if(isset($param['goes']) && !empty($param['goes'])){
            $where[] = ['cert.goes','=', $param['goes']];
        }
        if(isset($param['use']) && !empty($param['use'])){
            $where[] = ['cert.use','=', $param['use']];
        }
        if(isset($param['person_state']) && !empty($param['person_state'])){
            $where[] = ['person.state','=', $param['person_state']];
        }
        if(isset($param['cout_dt']) && !empty($param['cout_dt'])){
            $where[] = ['cert.cout_dt','between', explode(' - ', $param['cout_dt'])];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }
        if(isset($param['personid']) && !empty($param['personid'])){
            $where[] = ['cert.personid','=',$param['personid']];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['cert.chanid','in', (new MenuService())->get_chanid_sons($param['chanid'])];
        }

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';

        $data['state'] = (new CertService())->get_cert_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['statueuse'] = (new CertService())->get_cert_statueuse();
        $data['is_statueuse'] = isset($param['statueuse']) ? $param['statueuse'] : '';

        $data['goes'] = (new CertService())->get_cert_goes();
        $data['is_goes'] = isset($param['goes']) ? $param['goes'] : '';

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['is_nature'] = isset($param['nature']) ? $param['nature'] : '';

        $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
        $data['is_store_addr'] = isset($param['store_addr']) ? $param['store_addr'] : '';


        $data['data'] = CertModel::alias('cert')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->leftJoin('user u','u.id = cert.custodianid')
            ->field('cert.*,u.realname as custodian_name,person.name as person_name,person.state as person_state,
            person.nature as person_nature')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert', 'cert'))
            ->order('cert.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
                $item['state_name'] = (new CertService())->get_cert_state_name($item['state']);
                $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($item['statueuse']);
                $item['goes_name'] = (new CertService())->get_cert_goes_name($item['goes']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);

                $major = array_filter(explode('[]',$item['major']));
                $item['major_str'] = implode(' / ',$major);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                $arr = [];
                foreach($expiry_dtArr as $v){
                    if(empty($v)){
                        $arr[] = $v;
                    }else{
                        if($v < date('Y-m-d')){
                            $arr[] = '<span style="color:red;">'.$v.'</span>';
                        }else{
                            $arr[] = $v;
                        }
                    }
                }
                $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';

                $item['custodian_name'] = UserModel::get_realname_by_pk($item['custodianid']);
                $item['files'] = (new OptService())->get_file('cert', $item['id']);
                $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);
                $item['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$item['store_addr']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert');
        $data['token_roletype'] = $this->userinfo['token_roletype'];
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_cert_out(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','in', [2,3]];

        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['expiry_dt']) && !empty($param['expiry_dt'])){
            $expiry_dt = explode(' - ', $param['expiry_dt']);
            $ids = [];
            $c_data = CertModel::where(['deleted_user'=>0])->field('id,expiry_dt')->select();
            foreach ($c_data as $item){
                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                if($expiry_dtArr){
                    foreach ($expiry_dtArr as $dt){
                        if($dt >= $expiry_dt[0] && $dt <= $expiry_dt[1]){
                            $ids[] = $item['id'];
                        }
                    }
                }
            }
            $ids = array_unique($ids);
            $where[] = ['cert.id','in',$ids];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['cert.state','in', $param['state']];
        }
        if(isset($param['electron_dt']) && !empty($param['electron_dt'])){
            $where[] = ['cert.electron_dt','between', explode(' - ', $param['electron_dt'])];

        }
        if(isset($param['inspect_dt']) && !empty($param['inspect_dt'])){
            $where[] = ['cert.inspect_dt','between', explode(' - ', $param['inspect_dt'])];
        }
        if(isset($param['custodianid']) && !empty($param['custodianid'])){
            $where[] = ['u.realname','like', '%'.$param['custodianid'].'%'];
        }
        if(isset($param['store_addr']) && !empty($param['store_addr'])){
            $where[] = ['cert.store_addr','eq', $param['store_addr']];
        }

        if(isset($param['goes']) && !empty($param['goes'])){
            $where[] = ['cert.goes','=', $param['goes']];
        }
        if(isset($param['use']) && !empty($param['use'])){
            $where[] = ['cert.use','=', $param['use']];
        }
        if(isset($param['person_state']) && !empty($param['person_state'])){
            $where[] = ['person.state','=', $param['person_state']];
        }
        if(isset($param['cout_dt']) && !empty($param['cout_dt'])){
            $where[] = ['cert.cout_dt','between', explode(' - ', $param['cout_dt'])];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }
        if(isset($param['personid']) && !empty($param['personid'])){
            $where[] = ['cert.personid','=',$param['personid']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';

        $data['state'] = (new CertService())->get_cert_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['statueuse'] = (new CertService())->get_cert_statueuse();
        $data['is_statueuse'] = isset($param['statueuse']) ? $param['statueuse'] : '';

        $data['goes'] = (new CertService())->get_cert_goes();
        $data['is_goes'] = isset($param['goes']) ? $param['goes'] : '';

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['is_nature'] = isset($param['nature']) ? $param['nature'] : '';

        $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
        $data['is_store_addr'] = isset($param['store_addr']) ? $param['store_addr'] : '';


        $data['data'] = CertModel::alias('cert')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->leftJoin('user u','u.id = cert.custodianid')
            ->field('cert.*,u.realname as custodian_name,person.name as person_name,person.state as person_state,
            person.nature as person_nature')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_out', 'cert'))
            ->order('cert.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
                $item['state_name'] = (new CertService())->get_cert_state_name($item['state']);
                $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($item['statueuse']);
                $item['goes_name'] = (new CertService())->get_cert_goes_name($item['goes']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);

                $major = array_filter(explode('[]',$item['major']));
                $item['major_str'] = implode(' / ',$major);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                $arr = [];
                foreach($expiry_dtArr as $v){
                    if(empty($v)){
                        $arr[] = $v;
                    }else{
                        if($v < date('Y-m-d')){
                            $arr[] = '<span style="color:red;">'.$v.'</span>';
                        }else{
                            $arr[] = $v;
                        }
                    }
                }
                $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';

                $item['custodian_name'] = UserModel::get_realname_by_pk($item['custodianid']);
                $item['files'] = (new OptService())->get_file('cert', $item['id']);
                $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);
                $item['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$item['store_addr']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_out');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_cert(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['personid'])){
                return outputJson(4000, '请选择人员姓名');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择证书分类');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入证书名称');
            }
            if(empty($param['form'])){
                return outputJson(4000, '请选择证书形式');
            }

            $param['major'] = implode('[]',$param['major']);
            $param['expiry_dt'] = implode('[]',$param['expiry_dt']);

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = CertPersonModel::where(['id'=>$param['personid']])->value('chanid');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);


            Db::startTrans();
            try {
                $result = CertModel::create($param);
                (new OptService())->relation_file($files,'cert',$result->id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert', $result->id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert', $result->id, '证件');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $personid = $request->get('personid', 0, 'int');
            $data['personinfo'] = CertPersonModel::where(['id'=>$personid])->find();

            $data['type'] = (new OptService())->get_base_info('cert_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            $data['data']['custodian_info'] = (new UserService())->get_users_part_arr($this->userinfo['id'], 'user');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_cert(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['personid'])){
                return outputJson(4000, '请选择人员姓名');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择证书分类');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入证书名称');
            }
            if(empty($param['form'])){
                return outputJson(4000, '请选择证书形式');
            }

            $param['major'] = implode('[]',$param['major']);
            $param['expiry_dt'] = implode('[]',$param['expiry_dt']);
            $param['chanid'] = CertPersonModel::where(['id'=>$param['personid']])->value('chanid');

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                CertModel::update($param);
                (new OptService())->relation_file($files,'cert',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'cert', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'cert', $param['id'], '证件');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $result = CertModel::where(['id'=>$id])->find();
            if(!$result){
                return outputJson(4000,lang('code_4000'));
            }
            $result['major'] = explode('[]',$result['major']);
            $result['expiry_dt'] = explode('[]',$result['expiry_dt']);

            $result['custodian_info'] = (new UserService())->get_users_part_arr($result['custodianid'], 'user');
            $result['personinfo'] = CertPersonModel::where(['id'=>$result['personid']])->find();

            $data['data'] = $result;
            $data['type'] = (new OptService())->get_base_info('cert_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            $data['files'] = (new OptService())->get_file('cert', $result['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_cert(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = CertModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['major'] = str_replace('[]',',',$data['major']);
        $data['expiry_dt'] = str_replace('[]',',',$data['expiry_dt']);
        $data['dept_name'] = DeptModel::get_name_by_pk($data['deptid']);
        $data['custodian_name'] = UserModel::get_realname_by_pk($data['custodianid']);
        $data['person_name'] = CertPersonModel::where('id',$data['personid'])->value('name');
        $data['form_name'] = (new CertService())->get_cert_form_name($data['form']);
        $data['state_name'] = (new CertService())->get_cert_state_name($data['state']);
        $data['files'] = (new OptService())->get_file('cert', $data['id']);
        $data['type'] = (new OptService())->get_base_showname('cert_type',$data['type']);
        $data['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$data['store_addr']);
        $data['statueuse_name'] = (new CertService())->get_cert_statueuse_name($data['statueuse']);


        $use_list = [];
        $biduse = CertUseBidListModel::alias('list')
            ->field('use.bidid,list.*')
            ->leftJoin('cert_use_bid use', 'use.id = list.useid')
            ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
            ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1])
            ->where(['list.certid'=>$data['id']])
            ->select()->toArray();
        foreach ($biduse as $item){
            $bidinfo = BidModel::where(['id'=>$item['bidid']])->find();
            $item['enginid_name'] = $bidinfo['name'];
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($bidinfo['chanid']);
            $item['engin_state'] = (new BidService())->get_bid_state_name_tag($bidinfo);
            $item['business_name'] = $bidinfo['business'] == 1 ? '自营' : '联营';
            $use_list[] = $item;
        }

        $enginuse = CertUseListModel::alias('list')
            ->field('use.enginid,list.*')
            ->leftJoin('cert_use use', 'use.id = list.useid')
            ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
            ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1])
            ->where(['list.certid'=>$data['id']])
            ->select()->toArray();
        foreach ($enginuse as $item){
            $engininfo = EnginModel::where(['id'=>$item['enginid']])->find();
            $item['enginid_name'] = $engininfo['name'];
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($engininfo['chanid']);
            $item['engin_state'] = (new EnginService())->get_engin_state_name_tag($engininfo['id'],$engininfo['state']);
            $item['business_name'] = $engininfo['business'] == 1 ? '自营' : '联营';
            $use_list[] = $item;
        }
        $data['use_list'] = $use_list;


        $borrow_list = CertBorrowListModel::alias('list')
            ->field('bw.*,list.type,list.certid,list.guidt')
            ->leftJoin('cert_borrow bw', 'bw.id = list.mid')
            ->where(['bw.comid' => $this->userinfo['comid'], 'bw.deleted_user' => 0])
            ->where(['bw.isturn' => 1, 'bw.status' => 1])
            ->where(['list.certid'=>$data['id'],'list.type'=>1])
            ->select()->toArray();
        foreach ($borrow_list as &$item){
            $item['state_name'] = (new CertService())->get_cert_borrow_state_name($item['state']);
            if($item['qudt'] == '0000-00-00'){
                $item['qudt'] = '';
            }
            if($item['guidt'] == '0000-00-00'){
                $item['guidt'] = '';
            }
            $bill = FlowBillModel::where(['modenum'=>'cert_borrow','mid'=>$item['id']])->find();
            $item['sericnum'] = $bill['sericnum'];
        }
        $data['borrow_list'] = $borrow_list;

        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_cert(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的证书');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert', $data['id'], '证件');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function muladd_cert(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            if(!$list){
                return outputJson(4009,'请填写证书明细信息');
            }

            Db::startTrans();
            try {
                foreach ($list as $item){
                    $item['personid'] = $param['personid'];
                    $item['comid'] = $this->userinfo['comid'];
                    $item['created_user'] = $item['updated_user'] = $this->userinfo['id'];
                    $item['created_at'] = $item['updated_at']= date('Y-m-d H:i:s');
                    $item['deptid'] = $this->userinfo['deptid'];
                    $item['chanid'] = CertPersonModel::where(['id'=>$item['personid']])->value('chanid');
                    $item['major'] = str_replace('|','[]',$item['major']);

                    $result = CertModel::create($item);

                    if(isset($item['files'])){
                        FileModel::where('id','in',$item['files'])->update(['mid'=>$result->id,'table'=>'cert']);
                    }
                    (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert', $result->id);
                    (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert', $result->id, '证件');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new OptService())->get_base_info('cert_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            $data['data']['custodian_info'] = (new UserService())->get_users_part_arr($this->userinfo['id'], 'user');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function muledit_cert(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $paramids = explode(',', $param['ids']);

            Db::startTrans();
            try {
                foreach ($paramids as $paramid){
                    if($param['fieldname'] == 'type'){
                        CertModel::where(['id'=>$paramid])->update(['type'=>$param['type']]);
                    }
                    if($param['fieldname'] == 'form'){
                        CertModel::where(['id'=>$paramid])->update(['form'=>$param['form']]);
                    }
                    if($param['fieldname'] == 'state'){
                        CertModel::where(['id'=>$paramid])->update(['state'=>$param['state'],'out_dt'=>$param['out_dt']]);
                    }
                    if($param['fieldname'] == 'electron_dt'){
                        CertModel::where(['id'=>$paramid])->update(['electron_dt'=>$param['electron_dt']]);
                    }
                    if($param['fieldname'] == 'inspect_dt'){
                        CertModel::where(['id'=>$paramid])->update(['inspect_dt'=>$param['inspect_dt']]);
                    }
                    if($param['fieldname'] == 'custodianid'){
                        CertModel::where(['id'=>$paramid])->update(['custodianid'=>$param['custodianid']]);
                    }
                    if($param['fieldname'] == 'store_addr'){
                        CertModel::where(['id'=>$paramid])->update(['store_addr'=>$param['store_addr']]);
                    }

                    (new OptService())->add_flow_log('批量编辑', 'cert', $paramid);
                    (new OptService())->add_log_list('批量编辑', 'cert', $paramid, '证件');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new OptService())->get_base_info('cert_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function list_cert_expire_expiry(Request $request){
        $param = $request->post();

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];

        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }

        if(isset($param['electron_dt']) && !empty($param['electron_dt'])){
            $where[] = ['cert.electron_dt','between', explode(' - ', $param['electron_dt'])];

        }
        if(isset($param['inspect_dt']) && !empty($param['inspect_dt'])){
            $where[] = ['cert.inspect_dt','between', explode(' - ', $param['inspect_dt'])];
        }



        if(isset($param['cout_dt']) && !empty($param['cout_dt'])){
            $where[] = ['cert.cout_dt','between', explode(' - ', $param['cout_dt'])];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }
        if(isset($param['personid']) && !empty($param['personid'])){
            $where[] = ['cert.personid','=',$param['personid']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';



        $info = CertModel::alias('cert')
            ->field(Db::raw("cert.*,person.name as person_name,person.nature as person_nature,
            substring_index( substring_index( cert.expiry_dt, '[]', b.id), '[]', -1) AS expiry_dt,
            substring_index( substring_index( cert.major, '[]', b.id), '[]', -1) AS major"))
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->where((new MenuService())->get_miss_where('cert_expire_expiry', 'cert'))
            ->where($where)
            ->leftJoin('help_topic b',Db::raw("b.id < ( length( cert.expiry_dt ) - length( REPLACE ( cert.expiry_dt, '[]', '' ) ) )/2+2"))
            ->order("expiry_dt ASC")
            ->select()->toArray();


        $daytype = $request->param('daytype',0,'int');

        $list = [];
        foreach ($info as $kkk=>$vvv) {
            if(empty($vvv['expiry_dt'])){
                continue;
            }


            if($daytype == 1){
                $curDate = date('Y-m-d', strtotime(" +30 day"));
                if ($vvv['expiry_dt'] > date("Y-m-d") && $vvv['expiry_dt'] < $curDate) {
                    $list[] = $vvv;
                }
            }

            if($daytype == 2){
                $curDate = date('Y-m-d', strtotime(" +60 day"));
                if ($vvv['expiry_dt'] > date("Y-m-d") && $vvv['expiry_dt'] < $curDate) {
                    $list[] = $vvv;
                }
            }

            if($daytype == 3){
                $curDate = date('Y-m-d', strtotime(" +90 day"));
                if ($vvv['expiry_dt'] > date("Y-m-d") && $vvv['expiry_dt'] < $curDate) {
                    $list[] = $vvv;
                }
            }

            if($daytype == 4){
                $curDate = date('Y-m-d');
                if ($vvv['expiry_dt'] < $curDate) {
                    $list[] = $vvv;
                }
            }
        }


        foreach ($list as &$item){
            $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
            $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
            $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
            $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);
        }

        $data['data'] = $list;
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_cert_expire_electron(Request $request){
        $param = $request->post();

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];

        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }

        if(isset($param['electron_dt']) && !empty($param['electron_dt'])){
            $where[] = ['cert.electron_dt','between', explode(' - ', $param['electron_dt'])];

        }
        if(isset($param['inspect_dt']) && !empty($param['inspect_dt'])){
            $where[] = ['cert.inspect_dt','between', explode(' - ', $param['inspect_dt'])];
        }



        if(isset($param['cout_dt']) && !empty($param['cout_dt'])){
            $where[] = ['cert.cout_dt','between', explode(' - ', $param['cout_dt'])];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }
        if(isset($param['personid']) && !empty($param['personid'])){
            $where[] = ['cert.personid','=',$param['personid']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';


        $daytype = $request->param('daytype',0,'int');
        $whereDt = [];
        if($daytype == 1){
            $curDate = date('Y-m-d', strtotime(" +30 day"));
            $whereDt[] = ['electron_dt','gt',date("Y-m-d")];
            $whereDt[] = ['electron_dt','lt',$curDate];
        }
        if($daytype == 2){
            $curDate = date('Y-m-d', strtotime(" +60 day"));
            $whereDt[] = ['electron_dt','gt',date("Y-m-d")];
            $whereDt[] = ['electron_dt','lt',$curDate];
        }
        if($daytype == 3){
            $curDate = date('Y-m-d', strtotime(" +90 day"));
            $whereDt[] = ['electron_dt','gt',date("Y-m-d")];
            $whereDt[] = ['electron_dt','lt',$curDate];
        }

        if($daytype == 4){
            $curDate = date('Y-m-d');
            $whereDt[] = ['electron_dt','lt',$curDate];
            $whereDt[] = ['electron_dt','neq','null'];
            $whereDt[] = ['electron_dt','neq','0000-00-00'];
        }

        $data['data'] = CertModel::alias('cert')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->field('cert.*,person.name as person_name,person.nature as person_nature')
            ->where((new MenuService())->get_miss_where('cert_expire_electron', 'cert'))
            ->where($where)
            ->where($whereDt)
            ->order('electron_dt ASC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
                $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);

                $major = array_filter(explode('[]',$item['major']));
                $item['major_str'] = implode(' / ',$major);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                $arr = [];
                foreach($expiry_dtArr as $v){
                    if(empty($v)){
                        $arr[] = $v;
                    }else{
                        if($v < date('Y-m-d')){
                            $arr[] = '<span style="">'.$v.'</span>';
                        }else{
                            $arr[] = $v;
                        }
                    }
                }
                $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_cert_expire_inspect(Request $request){
        $param = $request->post();

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];

        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }




        if(isset($param['cout_dt']) && !empty($param['cout_dt'])){
            $where[] = ['cert.cout_dt','between', explode(' - ', $param['cout_dt'])];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }
        if(isset($param['personid']) && !empty($param['personid'])){
            $where[] = ['cert.personid','=',$param['personid']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';


        $daytype = $request->param('daytype',0,'int');
        $whereDt = [];
        if($daytype == 1){
            $curDate = date('Y-m-d', strtotime(" +30 day"));
            $whereDt[] = ['inspect_dt','gt',date("Y-m-d")];
            $whereDt[] = ['inspect_dt','lt',$curDate];
        }
        if($daytype == 2){
            $curDate = date('Y-m-d', strtotime(" +60 day"));
            $whereDt[] = ['inspect_dt','gt',date("Y-m-d")];
            $whereDt[] = ['inspect_dt','lt',$curDate];
        }
        if($daytype == 3){
            $curDate = date('Y-m-d', strtotime(" +90 day"));
            $whereDt[] = ['inspect_dt','gt',date("Y-m-d")];
            $whereDt[] = ['inspect_dt','lt',$curDate];
        }

        if($daytype == 4){
            $curDate = date('Y-m-d');
            $whereDt[] = ['inspect_dt','lt',$curDate];
            $whereDt[] = ['inspect_dt','neq','null'];
            $whereDt[] = ['inspect_dt','neq','0000-00-00'];
        }

        $data['data'] = CertModel::alias('cert')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->field('cert.*,person.name as person_name,person.nature as person_nature')
            ->where((new MenuService())->get_miss_where('cert_expire_inspect', 'cert'))
            ->where($where)
            ->where($whereDt)
            ->order('inspect_dt ASC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_form_name($item['form']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
                $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);

                $major = array_filter(explode('[]',$item['major']));
                $item['major_str'] = implode(' / ',$major);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                $arr = [];
                foreach($expiry_dtArr as $v){
                    if(empty($v)){
                        $arr[] = $v;
                    }else{
                        if($v < date('Y-m-d')){
                            $arr[] = '<span style="">'.$v.'</span>';
                        }else{
                            $arr[] = $v;
                        }
                    }
                }
                $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function get_cert_type(Request $request)
    {
        $numname = $request->param('numname', 'cert_type', 'string');
        $data = (new OptService())->get_base_info($numname);
        return outputJson(2000,lang('code_2000'),$data);
    }



    public function list_cert_company(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.pid','=','0'];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['cert.state','in', $param['state']];
        }
        if(isset($param['electron_dt']) && !empty($param['electron_dt'])){
            $where[] = ['cert.electron_dt','between', explode(' - ', $param['electron_dt'])];

        }
        if(isset($param['inspect_dt']) && !empty($param['inspect_dt'])){
            $where[] = ['cert.inspect_dt','between', explode(' - ', $param['inspect_dt'])];
        }
        if(isset($param['custodianid']) && !empty($param['custodianid'])){
            $where[] = ['u.realname','like', '%'.$param['custodianid'].'%'];
        }
        if(isset($param['store_addr']) && !empty($param['store_addr'])){
            $where[] = ['cert.store_addr','eq', $param['store_addr']];
        }
        if(isset($param['zinumber']) && !empty($param['zinumber'])){
            $where[] = ['cert.zinumber','like', '%'.$param['zinumber'].'%'];
        }
        if(isset($param['goes']) && !empty($param['goes'])){
            $where[] = ['cert.goes','=', $param['goes']];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_company_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';

        $data['state'] = (new CertService())->get_cert_company_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['goes'] = (new CertService())->get_cert_company_goes();
        $data['is_goes'] = isset($param['goes']) ? $param['goes'] : '';

        $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
        $data['is_store_addr'] = isset($param['store_addr']) ? $param['store_addr'] : '';


        $data['data'] = CertCompanyModel::alias('cert')
            ->leftJoin('user u','u.id = cert.custodianid')
            ->field('cert.*,u.realname as custodian_name')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_company', 'cert'))
            ->order('cert.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_company_form_name($item['form']);
                $item['state_name'] = (new CertService())->get_cert_company_state_name($item['state']);
                $item['goes_name'] = (new CertService())->get_cert_company_goes_name($item['goes']);
                $item['custodian_name'] = UserModel::get_realname_by_pk($item['custodianid']);
                $item['files'] = (new OptService())->get_file('cert', $item['id']);
                $item['type'] = (new OptService())->get_base_showname('cert_company_type', $item['type']);
                $item['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$item['store_addr']);

                $item['pidnum'] = CertCompanyModel::where(['deleted_user'=>0,'pid'=>$item['id']])->count();
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_company');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function detail_cert_company(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.pid','=',$param['pid']];


        $data['data'] = CertCompanyModel::alias('cert')
            ->leftJoin('user u','u.id = cert.custodianid')
            ->field('cert.*,u.realname as custodian_name')
            ->where($where)
            ->order('cert.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_company_form_name($item['form']);
                $item['state_name'] = (new CertService())->get_cert_company_state_name($item['state']);
                $item['goes_name'] = (new CertService())->get_cert_company_goes_name($item['goes']);
                $item['custodian_name'] = UserModel::get_realname_by_pk($item['custodianid']);
                $item['files'] = (new OptService())->get_file('cert', $item['id']);
                $item['type'] = (new OptService())->get_base_showname('cert_type', $item['type']);
                $item['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$item['store_addr']);

                $item['pidnum'] = CertCompanyModel::where(['deleted_user'=>0,'pid'=>$item['id']])->count();
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_cert_company(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['chanid'])){
                return outputJson(4000, '请选择所属单位');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择证书分类');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入证书名称');
            }
            if(empty($param['form'])){
                return outputJson(4000, '请选择证书形式');
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);
            Db::startTrans();
            try {
                $result = CertCompanyModel::create($param);
                (new OptService())->relation_file($files,'cert_company',$result->id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert_company', $result->id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert_company', $result->id, '证照');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new OptService())->get_base_info('cert_company_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            $data['data']['custodian_info'] = (new UserService())->get_users_part_arr($this->userinfo['id'], 'user');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_cert_company(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['chanid'])){
                return outputJson(4000, '请选择所属单位');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择证书分类');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入证书名称');
            }
            if(empty($param['form'])){
                return outputJson(4000, '请选择证书形式');
            }


            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);


            $zhuid = 0;
            $old = CertCompanyModel::where(['id'=>$param['id']])->find();
            if($old['pid'] == 0){
                $zhuid = $old['id'];
            }else{
                $zhuid = $old['pid'];
            }


            Db::startTrans();
            try {
                CertCompanyModel::update($param);

                //同步相关字段
                CertCompanyModel::where('id='.$zhuid.' or pid='.$zhuid)->update([
                    'chanid' => $param['chanid'],
                    'type' => $param['type'],
                    'name' => $param['name'],
                    'number' => $param['number'],
                    'introduce' => $param['introduce'],
                    'form' => $param['form'],
                    'state' => $param['state'],
                    'issue_unit' => $param['issue_unit'],
                    'issue_dt' => $param['issue_dt'],
                    'expiry_dt' => $param['expiry_dt'],
                    'inspect_dt' => $param['inspect_dt'],
                ]);


                (new OptService())->relation_file($files,'cert_company',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'cert_company', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'cert_company', $param['id'], '证照');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $result = CertCompanyModel::where(['id'=>$id])->find();
            if(!$result){
                return outputJson(4000,lang('code_4000'));
            }

            $result['custodian_info'] = (new UserService())->get_users_part_arr($result['custodianid'], 'user');
            $result['chanid_info'] = (new UserService())->get_users_part_arr($result['chanid'], 'dept');
            $data['data'] = $result;

            $data['type'] = (new OptService())->get_base_info('cert_company_type');
            $data['store_addr'] = (new OptService())->get_base_info('cert_store_addr');
            $data['form'] = (new CertService())->get_cert_form();
            $data['state'] = (new CertService())->get_cert_state();
            $data['files'] = (new OptService())->get_file('cert_company', $result['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_cert_company(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = CertCompanyModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['type'] = (new OptService())->get_base_showname('cert_company_type',$data['type']);
        $data['store_addr'] = (new OptService())->get_base_showname('cert_store_addr',$data['store_addr']);
        $data['chanid_name'] = DeptModel::get_name_by_pk($data['chanid']);
        $data['custodian_name'] = UserModel::get_realname_by_pk($data['custodianid']);
        $data['form_name'] = (new CertService())->get_cert_company_form_name($data['form']);
        $data['state_name'] = (new CertService())->get_cert_company_state_name($data['state']);
        $data['files'] = (new OptService())->get_file('cert_company', $data['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_cert_company(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的证书');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertCompanyModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertCompanyModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_company', $data['id'], '证件');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function copy_cert_company()
    {
        if($this->request->isPost()){
            $list = input('post.list',[]);
            if(!is_array($list) || empty($list)){
                return outputJson(4000,'请填写明细');
            }
            $list = array_filter($list);
            $id = input('post.id',0);
            $info = CertCompanyModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find()->toArray();
            if(!$info){
                return outputJson(4000,lang('code_4000'));
            }
            Db::startTrans();
            try{
                foreach ($list as $item){
                    $info['created_user'] = $this->userinfo['id'];
                    $info['created_at'] = date('Y-m-d H:i:s');
                    $info['updated_user'] = $this->userinfo['id'];
                    $info['updated_at'] = date('Y-m-d H:i:s');
                    $info['number'] = $item['number'];
                    $info['zinumber'] = $item['zinumber'];
                    $info['pid'] = $id;
                    unset($info['id']);

                    $files = array_filter($item['files']);
                    unset($item['files']);
                    foreach ($files as $k=>$v){
                        if(!isset($v['id'])){
                            unset($files[$k]);
                        }
                    }
                    $files = array_values($files);

                    $result = CertCompanyModel::create($info);
                    (new OptService())->relation_file($files,'cert_company',$result->id);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                halt($e);
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $number = input('get.number',0);
            $id = input('get.id',0);
            $info = CertCompanyModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
            if(!$info){
                return outputJson(4000,lang('code_4000'));
            }
            $list = [];
            // 查询证书的副本的最后一本 , 处理复制副本的证书编号
            $data = CertCompanyModel::where(['pid'=>$id,'deleted_user'=>0])->order('id desc')->find();
            if($data){
                $numArr = explode('-',$data['number']);
                $num = (int)end($numArr);
                array_pop($numArr);
                $name = implode('',$numArr);
                for($i=0;$i<(int)$number;$i++){
                    $list[] = $name.'-'.( (int)$num + $i + 1);
                }
            }else{
                for($i=0;$i<(int)$number;$i++){
                    $list[] = $info['number'].'-'.($i + 1);
                }
            }
            return outputJson(2000,lang('code_2000'),$list);
        }
    }

    public function list_cert_company_expire(Request $request){
        $param = $request->post();

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.pid','eq', 0];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['major']) && !empty($param['major'])){
            $where[] = ['cert.major','like', '%'.$param['major'].'%'];
        }
        if(isset($param['issue_unit']) && !empty($param['issue_unit'])){
            $where[] = ['cert.issue_unit','like', '%'.$param['issue_unit'].'%'];
        }
        if(isset($param['issue_dt']) && !empty($param['issue_dt'])){
            $where[] = ['cert.issue_dt','between', explode(' - ', $param['issue_dt'])];
        }
        if(isset($param['form']) && !empty($param['form'])){
            $where[] = ['cert.form','eq', $param['form']];
        }

        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['cert.type','=', $param['type']];
        }


        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['form'] = (new CertService())->get_cert_form();
        $data['is_form'] = isset($param['form']) ? $param['form'] : '';


        $daytype = $request->param('daytype',0,'int');
        $whereDt = [];
        if($daytype == 1){
            $curDate = date('Y-m-d');
            $biduiDate = date('Y-m-d', strtotime(" +30 day"));
            $whereDt = "(cert.expiry_dt > '".$curDate."' and cert.expiry_dt < '".$biduiDate."')";
            $whereDt .= " or (cert.inspect_dt > '".$curDate."' and cert.inspect_dt < '".$biduiDate."')";
        }
        if($daytype == 2){
            $curDate = date('Y-m-d');
            $biduiDate = date('Y-m-d', strtotime(" +60 day"));
            $whereDt = "(cert.expiry_dt > '".$curDate."' and cert.expiry_dt < '".$biduiDate."')";
            $whereDt .= " or (cert.inspect_dt > '".$curDate."' and cert.inspect_dt < '".$biduiDate."')";
        }
        if($daytype == 3){
            $curDate = date('Y-m-d');
            $biduiDate = date('Y-m-d', strtotime(" +90 day"));
            $whereDt = "(cert.expiry_dt > '".$curDate."' and cert.expiry_dt < '".$biduiDate."')";
            $whereDt .= " or (cert.inspect_dt > '".$curDate."' and cert.inspect_dt < '".$biduiDate."')";
        }

        if($daytype == 4){
            $curDate = date('Y-m-d');
            $whereDt = "(cert.expiry_dt < '".$curDate."' and cert.expiry_dt != '0000-00-00' and cert.expiry_dt is not null)";
            $whereDt .= "or (cert.inspect_dt < '".$curDate."' and cert.inspect_dt != '0000-00-00' and cert.inspect_dt is not null)";
        }

        $data['data'] = CertCompanyModel::alias('cert')
            ->field('cert.*')
            ->where((new MenuService())->get_miss_where('cert_company_expire', 'cert'))
            ->where($where)
            ->where($whereDt)
            ->order('expiry_dt ASC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key)use($daytype){
                $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['form_name'] = (new CertService())->get_cert_company_form_name($item['form']);
                $item['type'] = (new OptService())->get_base_showname('cert_company_type', $item['type']);

                if($item['expiry_dt'] == '0000-00-00'){
                    $item['expiry_dt'] = '';
                }
                if($item['inspect_dt'] == '0000-00-00'){
                    $item['inspect_dt'] = '';
                }

                if($daytype == 1){
                    $biduiDate = date('Y-m-d', strtotime(" +30 day"));
                    if($item['expiry_dt'] < $biduiDate){
                        $item['expiry_dt'] = '<span class="colorhong">'.$item['expiry_dt'].'</span>';
                    }
                    if($item['inspect_dt'] < $biduiDate){
                        $item['inspect_dt'] = '<span class="colorhong">'.$item['inspect_dt'].'</span>';
                    }
                }
                if($daytype == 2){
                    $biduiDate = date('Y-m-d', strtotime(" +60 day"));
                    if($item['expiry_dt'] < $biduiDate){
                        $item['expiry_dt'] = '<span class="colorhong">'.$item['expiry_dt'].'</span>';
                    }
                    if($item['inspect_dt'] < $biduiDate){
                        $item['inspect_dt'] = '<span class="colorhong">'.$item['inspect_dt'].'</span>';
                    }
                }
                if($daytype == 3){
                    $biduiDate = date('Y-m-d', strtotime(" +90 day"));
                    if($item['expiry_dt'] < $biduiDate){
                        $item['expiry_dt'] = '<span class="colorhong">'.$item['expiry_dt'].'</span>';
                    }
                    if($item['inspect_dt'] < $biduiDate){
                        $item['inspect_dt'] = '<span class="colorhong">'.$item['inspect_dt'].'</span>';
                    }
                }

                if($daytype == 4){
                    $curDate = date('Y-m-d');
                    if($item['expiry_dt'] < $curDate){
                        $item['expiry_dt'] = '<span class="colorhong">'.$item['expiry_dt'].'</span>';
                    }
                    if($item['inspect_dt'] < $curDate){
                        $item['inspect_dt'] = '<span class="colorhong">'.$item['inspect_dt'].'</span>';
                    }
                }


                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }



    public function list_achieve(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['ach.deleted_user','=','0'];
        $where[] = ['ach.comid','=',$this->userinfo['comid']];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['ach.name','like','%'.$param['name'].'%'];
        }
        if(isset($param['year']) && !empty($param['year'])){
            $where[] = ['ach.year','=',$param['year']];
        }
        if(isset($param['jian_unit']) && !empty($param['jian_unit'])){
            $where[] = ['ach.jian_unit','like','%'.$param['jian_unit'].'%'];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['e.type','=', $param['type']];
        }
        if(isset($param['addr']) && !empty($param['addr'])){
            $where[] = ['ach.addr','like','%'.$param['addr'].'%'];
        }
        if(isset($param['start_money']) && !empty($param['start_money'])){
            $where[] = ['ach.money','>=',$param['start_money']];
        }
        if(isset($param['end_money']) && !empty($param['end_money'])){
            $where[] = ['ach.money','<=',$param['end_money']];
        }
        if(isset($param['start_dt']) && !empty($param['start_dt'])){
            $where[] = ['ach.start_dt','between',explode(' - ',$param['start_dt'])];
        }
        if(isset($param['end_dt']) && !empty($param['end_dt'])){
            $where[] = ['ach.end_dt','between',explode(' - ',$param['end_dt'])];
        }
        if(isset($param['jingperson_name']) && !empty($param['jingperson_name'])){
            $where[] = ['jing.name','like','%'.$param['jingperson_name'].'%'];
        }
        if(isset($param['shuperson_name']) && !empty($param['shuperson_name'])){
            $where[] = ['shu.name','like','%'.$param['shuperson_name'].'%'];
        }

        $data['type'] = (new OptService())->get_base_info('engin_engintype');
        $data['is_type'] = isset($param['type']) ? $param['type'] : '';

        $data['data'] = AchieveModel::alias('ach')
            ->field('ach.*,jing.name as jingperson_name,shu.name as shuperson_name')
            ->leftJoin('cert_person jing','jing.id = ach.jingperson')
            ->leftJoin('cert_person shu','shu.id = ach.shuperson')
            ->where($where)
            ->where((new MenuService())->get_miss_where('achieve', 'ach'))
            ->order('ach.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type_name'] = (new OptService())->get_base_showname('engin_engintype', $item['type']);
                return $item;
            })->toArray();

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['butauth'] = (new MenuService())->get_butauth('achieve');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_achieve(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入项目名称');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择项目类型');
            }
            if(empty($param['money'])){
                return outputJson(4000, '请输入合同金额');
            }

            $param['jingperson'] = CertModel::where(['id'=>$param['jingcert']])->value('personid');
            $param['shuperson'] = CertModel::where(['id'=>$param['shucert']])->value('personid');

            if(!$param['jingperson']){
                $param['jingperson'] = 0;
            }
            if(!$param['shuperson']){
                $param['shuperson'] = 0;
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $result = AchieveModel::create($param);


                (new OptService())->relation_file($files,'achieve',$result->id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'achieve', $result->id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'achieve', $result->id, '业绩');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new OptService())->get_base_info('engin_engintype');
            $data['addr'] = (new OptService())->get_city_cader();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_achieve(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入项目名称');
            }
            if(empty($param['type'])){
                return outputJson(4000, '请选择项目类型');
            }
            if(empty($param['money'])){
                return outputJson(4000, '请输入合同金额');
            }

            $param['jingperson'] = CertModel::where(['id'=>$param['jingcert']])->value('personid');
            $param['shuperson'] = CertModel::where(['id'=>$param['shucert']])->value('personid');

            if(!$param['jingperson']){
                $param['jingperson'] = 0;
            }
            if(!$param['shuperson']){
                $param['shuperson'] = 0;
            }

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at']= date('Y-m-d H:i:s');

            Db::startTrans();
            try {
                AchieveModel::update($param);

                AchieveListModel::where('mid',$param['id'])->delete();
                if(isset($param['xiang_cert']) && !empty($param['xiang_cert'])){
                    AchieveListModel::create([
                        'mid' => $param['id'],
                        'place' => '项目经理',
                        'cert_id' => $param['xiang_cert']
                    ]);
                }
                if(isset($param['ji_cert']) && !empty($param['ji_cert'])){
                    AchieveListModel::create([
                        'mid' => $param['id'],
                        'place' => '技术负责人',
                        'cert_id' => $param['ji_cert']
                    ]);
                }

                (new OptService())->relation_file($files,'achieve',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'achieve', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'achieve', $param['id'], '业绩');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $result = AchieveModel::where(['id'=>$id])->find();
            if(!$result){
                return outputJson(4000,lang('code_4000'));
            }

            $result['jingcert_info'] = CertModel::where(['id'=>$result['jingcert']])->find();
            if($result['jingcert_info']){
                $result['jingcert_info']['personname'] = CertPersonModel::where(['id'=>$result['jingcert_info']['personid']])->value('name');
            }

            $result['shucert_info'] = CertModel::where(['id'=>$result['shucert']])->find();
            if($result['shucert_info']){
                $result['shucert_info']['personname'] = CertPersonModel::where(['id'=>$result['shucert_info']['personid']])->value('name');
            }

            $data['data'] = $result;

            $data['files'] = (new OptService())->get_file('achieve', $result['id']);
            $data['type'] = (new OptService())->get_base_info('engin_engintype');
            $data['addr'] = (new OptService())->get_city_cader();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_achieve(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = AchieveModel::where('id',$id)->find();
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['type'] = (new OptService())->get_base_showname('engin_engintype',$data['type']);

        $data['jingcert_info'] = CertModel::where(['id'=>$data['jingcert']])->find();
        if($data['jingcert_info']){
            $data['jingcert_info']['personname'] = CertPersonModel::where(['id'=>$data['jingcert_info']['personid']])->value('name');
        }

        $data['shucert_info'] = CertModel::where(['id'=>$data['shucert']])->find();
        if($data['shucert_info']){
            $data['shucert_info']['personname'] = CertPersonModel::where(['id'=>$data['shucert_info']['personid']])->value('name');
        }

        $data['files'] = (new OptService())->get_file('achieve', $data['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_achieve(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择数据');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = AchieveModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                AchieveModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'achieve', $data['id'], '业绩');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function muladd_achieve(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);

            Db::startTrans();
            try {
                foreach ($list as $item){
                    $item['comid'] = $this->userinfo['comid'];
                    $item['created_user'] = $item['updated_user'] = $this->userinfo['id'];
                    $item['created_at'] = $item['updated_at']= date('Y-m-d H:i:s');
                    $item['deptid'] = $this->userinfo['deptid'];
                    $item['chanid'] = (new UserService())->get_user_chanid();

                    $item['jingperson'] = CertModel::where(['id'=>$item['jingcert']])->value('personid');
                    $item['shuperson'] = CertModel::where(['id'=>$item['shucert']])->value('personid');


                    $item['jingperson'] = CertModel::where(['id'=>$item['jingcert']])->value('personid');
                    $item['shuperson'] = CertModel::where(['id'=>$item['shucert']])->value('personid');
                    $result = AchieveModel::create($item);


                    if(isset($item['files'])){
                        FileModel::where('id','in',$item['files'])->update(['mid'=>$result->id,'table'=>'achieve']);
                    }
                    (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'achieve', $result->id);
                    (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'achieve', $result->id, '业绩');
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['type'] = (new OptService())->get_base_info('engin_engintype');
            $data['addr'] = (new OptService())->get_city_cader();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }




    public function list_cert_employ(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['employ.deleted_user','=','0'];
        $where[] = ['employ.comid','=',$this->userinfo['comid']];


        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['employ.chanid','=', $param['chanid']];
        }
        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=', $param['person_nature']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['employ.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['sign_dt']) && !empty($param['sign_dt'])){
            $where[] = ['employ.sign_dt','=', $param['sign_dt']];
        }
        if(isset($param['qualification']) && !empty($param['qualification'])){
            $where[] = ['employ.qualification','like','%'.$param['qualification'].'%'];
        }
        if(isset($param['channel']) && !empty($param['channel'])){
            $where[] = ['employ.channel','eq',$param['channel']];
        }
        if(isset($param['purpose']) && !empty($param['purpose'])){
            $where[] = ['employ.purpose','eq',$param['purpose']];
        }
        if(isset($param['iszhu']) && !empty($param['iszhu'])){
            $where[] = ['employ.iszhu','eq',$param['iszhu']];
        }
        if(isset($param['pay_type']) && !empty($param['pay_type'])){
            $where[] = ['employ.pay_type','eq',$param['pay_type']];
        }
        if(isset($param['start_dt']) && !empty($param['start_dt'])){
            $where[] = ['employ.start_dt','=', $param['start_dt']];
        }
        if(isset($param['end_dt']) && !empty($param['end_dt'])){
            $where[] = ['employ.end_dt','=', $param['end_dt']];
        }
        if(isset($param['account_num']) && !empty($param['account_num'])){
            $where[] = ['employ.account_num','like', '%'.$param['account_num'].'%'];
        }


        $iszhu = CertEmployModel::get_iszhu();
        $pay_type = CertEmployModel::get_pay_type();
        $data['data'] = CertEmployModel::alias('employ')
            ->leftJoin('cert_person person','person.id = employ.personid')
            ->field('employ.*,person.name as person_name')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_employ', 'employ'))
            ->order('employ.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key)use ($iszhu,$pay_type){
                $item['chan_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['iszhu_name'] = isset($iszhu[$item['iszhu']]) ? $iszhu[$item['iszhu']] : '';
                $item['pay_type'] = isset($pay_type[$item['pay_type']]) ? $pay_type[$item['pay_type']] : '';
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
                $item['channel'] = (new OptService())->get_base_showname('cert_employ_channel',$item['channel']);
                $item['purpose'] = (new OptService())->get_base_showname('cert_employ_purpose',$item['purpose']);

                $qualification = array_filter(explode(',',$item['qualification']));
                $item['qualification'] = '';
                foreach ($qualification as $v){
                    $item['qualification'] .= empty($item['qualification']) ? (new OptService())->get_base_showname('cert_employ_qualification', $v)
                        : '，'.(new OptService())->get_base_showname('cert_employ_qualification', $v);
                }
                return $item;
            })
            ->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_employ');
        $data['iszhu'] = $iszhu;
        $data['channel'] = (new OptService())->get_base_info('cert_employ_channel');
        $data['qualification'] = (new OptService())->get_base_info('cert_employ_qualification');
        $data['purpose'] = (new OptService())->get_base_info('cert_employ_purpose');
        $data['pay_type'] = $pay_type;
        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['person_nature'] = (new OptService())->get_base_info('person_nature');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_cert_employ(Request $request){
        if($request->isPost()){
            $param = $request->post();
             $check = $this->validate($param,'CertEmploy.add');
             if($check !== true){
                 return outputJson(4000,$check);
             }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $result = CertEmployModel::create($param);

                // 生成聘费报表 1月付  2年付
                $this->generate_cert_employ_money($result->id,$param['pay_type'],$param['personid'],$param['start_dt'],$param['end_dt'],$param['money'],0);

                (new OptService())->relation_file($files,'cert_employ',$result->id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert_employ', $result->id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert_employ', $result->id, '外聘');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $personid = $request->get('personid', 0, 'int');
            $person = CertPersonModel::where(['id'=>$personid])->find();
            $data['person'] = $person;

            $data['channel'] = (new OptService())->get_base_info('cert_employ_channel');
            $data['qualification'] = (new OptService())->get_base_info('cert_employ_qualification');
            $data['purpose'] = (new OptService())->get_base_info('cert_employ_purpose');
            $data['pay_type'] = CertEmployModel::get_pay_type();
            $data['iszhu'] = CertEmployModel::get_iszhu();
            $data['person_nature'] = (new OptService())->get_base_info('person_nature');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_cert_employ(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $check = $this->validate($param,'CertEmploy.edit');
            if($check !== true){
                return outputJson(4000,$check);
            }
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                CertEmployModel::update($param);

                // 生成每月数据 1月付  2年付
                $this->generate_cert_employ_money($param['id'],$param['pay_type'],$param['personid'],$param['start_dt'],$param['end_dt'],$param['money'],0);

                (new OptService())->relation_file($files,'cert_employ',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'cert_employ', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'cert_employ', $param['id'], '外聘');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $result = CertEmployModel::where(['id'=>$id])->find();
            if(!$result){
                return outputJson(4000,lang('code_4000'));
            }
            $result['person_name'] = CertPersonModel::where('id',$result['personid'])->value('name');
            $result['qualification'] = explode(',',$result['qualification']);
            $data['data'] = $result;
            $data['files'] = (new OptService())->get_file('cert_employ', $result['id']);
            $data['channel'] = (new OptService())->get_base_info('cert_employ_channel');
            $data['qualification'] = (new OptService())->get_base_info('cert_employ_qualification');
            $data['purpose'] = (new OptService())->get_base_info('cert_employ_purpose');
            $data['pay_type'] = CertEmployModel::get_pay_type();
            $data['iszhu'] = CertEmployModel::get_iszhu();
            $data['person_nature'] = (new OptService())->get_base_info('person_nature');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function show_cert_employ(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = CertEmployModel::where('id',$id)->find();
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $iszhu = CertEmployModel::get_iszhu();
        $data['iszhu_name'] = isset($iszhu[$data['iszhu']]) ? $iszhu[$data['iszhu']] : '';
        $pay_type = CertEmployModel::get_pay_type();
        $data['pay_type'] = isset($pay_type[$data['pay_type']]) ? $pay_type[$data['pay_type']] : '';
        $data['person_name'] = CertPersonModel::where('id',$data['personid'])->value('name');
        $data['channel'] = (new OptService())->get_base_showname('cert_employ_channel', $data['channel']);

        $qualification = array_filter(explode(',',$data['qualification']));
        $data['qualification'] = '';
        foreach ($qualification as $v){
            $data['qualification'] .= empty($data['qualification']) ? (new OptService())->get_base_showname('cert_employ_qualification', $v)
                : '，'.(new OptService())->get_base_showname('cert_employ_qualification', $v);
        }
        $data['purpose'] = (new OptService())->get_base_showname('cert_employ_purpose', $data['purpose']);
        $data['person_nature'] = (new OptService())->get_base_showname('person_nature', $data['person_nature']);
        $data['files'] = (new OptService())->get_file('cert_employ', $data['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_cert_employ(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的证书');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertEmployModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertEmployModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_company', $data['id'], '外聘');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function list_cert_employ_count()
    {
        if($this->request->isPost()){
            $param = input('post.');
            get_page($param);

            $year = $param['year'];
            $where = [];

            if(isset($param['chanid']) && !empty($param['chanid'])){
                $where[] = ['e.chanid','=', $param['chanid']];
            }
            if(isset($param['person_nature']) && !empty($param['person_nature'])){
                $where[] = ['p.nature','=', $param['person_nature']];
            }
            if(isset($param['person_name']) && !empty($param['person_name'])){
                $where[] = ['p.name','like', '%'.$param['person_name'].'%'];
            }
            if(isset($param['person_state']) && !empty($param['person_state'])){
                $where[] = ['p.state','=', $param['person_state']];
            }
            if(isset($param['number']) && !empty($param['number'])){
                $where[] = ['e.number','like', '%'.$param['number'].'%'];
            }
            if(isset($param['qualification']) && !empty($param['qualification'])){
                $where[] = ['e.qualification','like','%'.$param['qualification'].'%'];
            }


            // 查询所有在职人员信息
            $personIdArr = CertPersonModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])->column('id');

            // 查询合同信息
            $iszhu = CertEmployModel::get_iszhu();
            $pay_type = CertEmployModel::get_pay_type();
            $data['data'] = CertEmployModel::alias('e')->field('e.*,p.name,p.nature,p.chanid as p_chanid,p.state')
                ->leftJoin('cert_person p','p.id = e.personid')
                ->where($where)
                ->where(['e.deleted_user'=>0])
                ->where((new MenuService())->get_miss_where('cert_employ_count', 'e'))
                ->where('e.personid','in',$personIdArr)
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function($item,$key)use($year,$iszhu,$pay_type){
                    $item['chan_name'] = DeptModel::get_name_by_pk($item['p_chanid']);
                    $item['nature'] = (new OptService())->get_base_showname('person_nature',$item['nature']);

                    $item['pay_type'] = isset($pay_type[$item['pay_type']]) ? $pay_type[$item['pay_type']] : '';
                    $item['iszhu'] = isset($iszhu[$item['iszhu']]) ? $iszhu[$item['iszhu']] : '';
                    $item['purpose'] = (new OptService())->get_base_showname('cert_employ_purpose',$item['purpose']);
                    $item['channel'] = (new OptService())->get_base_showname('cert_employ_channel',$item['channel']);

                    $qualification = $item['qualification'];
                    $qualification = array_filter(explode(',',$qualification));
                    $qualificationArr = [];
                    foreach($qualification as $v){
                        $qualificationArr[] = (new OptService())->get_base_showname('cert_employ_qualification',$v);
                    }
                    $item['qualification'] = implode(',',$qualificationArr);

                    // 查询每月费用
                    $item['count'] = 0;
                    $fee_data = CertEmployFeeModel::where(['personid'=>$item['personid']])->where('ym','like',$year.'%')->select()->toArray();
                    foreach($fee_data as $v){
                        $item['ym'.substr($v['ym'],'0',7)] = $v['money'];
                        $item['count'] += $v['money'];
                    }
                    $item['count'] = sprintf("%1\$.2f",$item['count']);
                })->toArray();

            $data['chanid'] = (new UserService())->get_chaninfo_all();
            $data['qualification'] = (new OptService())->get_base_info('cert_employ_qualification');
            $data['person_nature'] = (new OptService())->get_base_info('person_nature');
            $data['person_state'] = ['在职','离职'];

            return outputJson(2000,lang('code_2000'),$data);

        }else{
            $year = input('get.year', date('Y'));
            $col[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=>'left'];
            $col[] = ['field' => 'name', 'title' => '人员姓名','merge'=>true,'event'=>'name','style'=>'color: #409EFF!important;cursor: pointer;'];
            $col[] = ['field' => 'nature', 'title' => '人员性质','merge'=>['name']];
            $col[] = ['field' => 'chan_name', 'title' => '所属公司','merge'=>['name']];
            $col[] = ['field' => 'state', 'title' => '人员状态','merge'=>['name']];
            $col[] = ['field' => 'number', 'title' => '合同编号'];
            $col[] = ['field' => 'qualification', 'title' => '聘用资格'];
            $col[] = ['field' => 'channel', 'title' => '聘用渠道'];
            $col[] = ['field' => 'purpose', 'title' => '用途'];
            $col[] = ['field' => 'iszhu', 'title' => '是否可驻场'];
            $col[] = ['field' => 'money', 'title' => '聘费(元)'];
            $col[] = ['field' => 'pay_type', 'title' => '聘费支付方式'];
            $col[] = ['field' => 'start_dt', 'title' => '聘期开始时间'];
            $col[] = ['field' => 'end_dt', 'title' => '聘期结束时间'];
            for($i=1;$i<=12;$i++){
                if($i < 10){
                    $m = '0'.$i;
                }else{
                    $m = $i;
                }
                $title = $year.'-'.$m;
                $field = 'ym'.$title;
                $col[] = ['field' => $field, 'title' => $title];
            }
            $col[] = ['field' => 'count', 'title' => '合计'];
            $data['cols'] = $col;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function generate_cert_employ_money($id,$pay_type,$personid,$c_startdt,$c_enddt,$c_money){
        if($pay_type == 1){ # 月付
            CertEmployFeeModel::where('mid',$id)->delete();
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            if($ys.'-'.$ms == $ye.'-'.$me) { # 同月
                $md = date('t',strtotime($ys.'-'.$ms.'-01'));
                $money = $c_money * ((int)$de - (int)$ds + 1) / $md;

                $array = [
                    'mid' => $id,
                    'personid' => $personid,
                    'ym' => $ys . '-' . $ms.'-01',
                    'money' => $money,
                ];
                CertEmployFeeModel::create($array);

            } else { # 跨年，判断是否满一年，结束时间是否大于系统生成的结束时间，如果不满一年，按照天数/上一年的总天数*年聘费
                for($year = (int)$ys; $year <= (int)$ye; $year++) {
                    if ($year == $ys && $year == $ye) { // 同年
                        $start_month = (int)$ms;
                        $end_month = (int)$me;
                    } else if ($year == $ys) { // 跨年，初始年份
                        $start_month = (int)$ms;
                        $end_month = 12;
                    } else if ($year == $ye) { // 跨年，结束年份
                        $start_month = 1;
                        $end_month = (int)$me;
                    } else{ // 跨年，中间年份
                        $start_month = 1;
                        $end_month = 12;
                    }

                    for ($i = $start_month; $i <= $end_month; $i++) {
                        if ($i < 10) {
                            $month = '0' . $i;
                        } else {
                            $month = $i;
                        }
                        if($year.'-'.$month == $ys.'-'.$ms){ # 开始月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * ($md - intval($ds) + 1) / $md;
                        }else if($year.'-'.$month == $ye.'-'.$me){ # 结束月份
                            $md = date('t',strtotime($year.'-'.$month.'-01'));
                            $money = $c_money * $de / $md;
                        }else{
                            $money = $c_money;
                        }

                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => $year . '-' . $month.'-01',
                            'money' => $money,
                        ];
                        CertEmployFeeModel::create($array);
                    }
                }
            }

        }else{ # 年付  结束时间 > 开始时间+1年，则满一年   否则计算天数/年天数*金额
            CertEmployFeeModel::where('mid',$id)->delete();
            // 遍历时间段
            list($ys,$ms,$ds) = explode('-',$c_startdt);
            list($ye,$me,$de) = explode('-',$c_enddt);

            $temp_date = $c_startdt;



            for($year = $ys; $year <= $ye; $year++) {
                $temp_ = date('Y-m-d',strtotime($temp_date."+1 year - 1 day"));


                if($temp_ <= $c_enddt){
                    $array = [
                        'mid' => $id,
                        'personid' => $personid,
                        'ym' => date("Y-m-01", strtotime($temp_date)),
                        'money' => $c_money,
                        'startdt' => $temp_date,
                        'enddt' => $temp_,
                    ];

                    $temp_date = date('Y-m-d',strtotime($temp_."+1 day"));
                    CertEmployFeeModel::create($array);
                    if($temp_ == $c_enddt){
                        break;
                    }
                }else{
                    if(substr($temp_,0,7) == substr($c_enddt,0,7)){ # +1年和结束时间为同年, 跨年计算
                        $money = 0;
                        // 首年
                        $year_day = (new CertService())->cal_days_in_year(substr($temp_date,0,4));
                        $day = count_days($temp_date, substr($temp_date,0,4).'-12-31');
                        $money += ($day / $year_day) * $c_money;

                        // 尾年
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $day = count_days($c_enddt, substr($c_enddt,0,4).'-12-31') - 1;
                        $money += (($year_day - $day) / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }else{ # 同年计算
                        $day = count_days($temp_date, $c_enddt) - 1;
                        $year_day = (new CertService())->cal_days_in_year(substr($c_enddt,0,4));
                        $money = ($day / $year_day) * $c_money;
                        $array = [
                            'mid' => $id,
                            'personid' => $personid,
                            'ym' => date("Y-m-01", strtotime($temp_date)),
                            'money' => $money,
                            'startdt' => $temp_date,
                            'enddt' => $c_enddt,
                        ];
                    }
                    CertEmployFeeModel::create($array);
                    break;
                }
            }
        }
    }



    public function list_cert_use(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['use.deleted_user','=','0'];
        $where[] = ['use.comid','=',$this->userinfo['comid']];
        $where[] = ['use.isturn','=',1];
        $where[] = ['use.status','in',[0,1]];


        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['use.chanid','=', $param['chanid']];
        }
        if(isset($param['flowuser']) && $param['flowuser'] != ''){
            $where[] = ['use.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['flowuser']) && $param['flowuser'] != ''){
            $where[] = ['use.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $created_at = explode(' - ', $param['created_at']);
            $st_at = $created_at[0].' 00:00:00';
            $end_at = $created_at[0].' 23:59:59';
            $where[] = ['use.created_at','between', [$st_at,$end_at]];
        }
        if(isset($param['enginid_name']) && $param['enginid_name'] != ''){
            $where[] = ['e.name','like', '%'.$param['enginid_name'].'%'];
        }

        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['use.dt','between', explode(' - ', $param['dt'])];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['use.status','=', $param['status']];
        }



        $data['chanid'] = (new UserService())->get_chaninfo_all();;
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';


        $data['data'] = CertUseModel::alias('use')
            ->leftJoin('engin e','e.id = use.enginid')
            ->field('use.*,e.name as engin_name')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_use', 'e'))
            ->order('use.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['num'] = CertUseListModel::where(['useid'=>$item['id']])->count();
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_use');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function show_cert_use(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = CertUseModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }


        $engininfo = EnginModel::where(['id'=>$data['data']['enginid']])->find();
        $data['engininfo'] = $engininfo;



        $list = CertUseListModel::where(['useid'=>$data['data']['id']])->select()->toArray();
        foreach ($list as &$item){
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['person_name'] = CertPersonModel::where(['id'=>$certInfo['personid']])->value('name');
            $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($certInfo['statueuse']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($certInfo['chanid']);
            $item['opt_name'] = $item['opt'] > 0 ? '在用' : '停用';
        }
        $data['list'] = $list;

        $data['files'] = (new OptService())->get_file('cert_use', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_cert_use(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的证书');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertUseModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertUseModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_use', $data['id'], '用证');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function down_cert_use(Request $request)
    {
        if($this->request->isPost()){
            $id = $request->post('id',0,'int');
            $ids = $request->post('ids','','string');
            $ids = array_filter($ids);
            Db::startTrans();
            try {
                $useInfo = CertUseModel::where('id',$id)->find();
                $engin_name = EnginModel::where(['id'=>$useInfo['enginid']])->value('name');
                $data = (new OptService())->down_watermark_zip($ids, '报建用证附件下载', $engin_name);

                (new OptService())->add_flow_log('下载', 'cert_use', $id);
                (new OptService())->add_log_list('下载', 'cert_use', $id, '报建用证');
                Db::commit();
                return outputJson(2000, lang('code_2000'),$data);
            } catch (\Exception $e){
                Db::rollback();
                return outputJson(4000, $e->getMessage());
            }
        }else{
            $id = $request->get('id',0,'int');
            $data = CertUseModel::where(['id'=>$id])->find();
            $certids_arr = CertUseListModel::where(['useid'=>$data['id']])->distinct(true)->column('certid');
            $personids = CertModel::where('id','in',$certids_arr)->distinct(true)->column('personid');
            $list = [];
            foreach ($personids as $pid) {
                $name = CertpersonModel::where('id',$pid)->value('name');
                $array = [
                    'name' => $name,
                    'len' => 0,
                    'children' => [],
                ];
                // 查询人员用证的证书
                $certIdArr = CertModel::where(['deleted_user'=>0,'personid'=>$pid])->column('id');
                foreach ($certIdArr as $certid){
                    if(in_array($certid,$certids_arr)){
                        $certArr['name'] = CertModel::where('id',$certid)->value('name');
                        // 查询证书的附件
                        $certArr['children'] = FileModel::where(['table'=>'cert','mid'=>$certid])->field('id,name')->select()->toArray();
                        $certArr['len'] = count($certArr['children']);
                        if(count($certArr['children']) == 0){
                            $array['len'] += 1;
                        }else{
                            $array['len'] += count($certArr['children']);
                        }
                        $array['children'][] = $certArr;
                    }
                }
                $array['len'] += 1;
                $list[] = $array;
            }

            return outputJson(2000,lang('code_2000'),$list);
        }
    }
    public function check_cert_use(Request $request){
        $str = "";
        $checkStatus = false;
        if($request->isPost()){
            $param = $request->post();

            $list = array_filter($param['list']);
            if(count($list) < 1){
                return outputJson(4000, '请输入用证明细');
            }
            foreach ($list as $kkk=>$vvv){
               $certinfo = CertModel::where(['id'=>$vvv['certid']])->find();
               $statueuse = $certinfo['statueuse'];
               $statueuse_name = (new CertService())->get_cert_statueuse_name($statueuse);
               if($statueuse == 1){
                    $exist = CertUseListModel::alias('list')
                        ->join('cert_use use','use.id=list.useid')
                        ->where(['use.comid'=>$this->userinfo['comid'],'use.deleted_user'=>0])
                        ->where(['use.isturn'=>1,'use.status'=>0])
                        ->where(['list.certid'=>$vvv['certid']])
                        ->find();
                    if($exist){
                        $checkStatus = true;
                        $str .= "第".$kkk."行证书当前使用情况为空闲,但在流程申请中</br>";
                    }else{
                        $exist = CertUseBidListModel::alias('list')
                            ->join('cert_use_bid use','use.id=list.useid')
                            ->where(['use.comid'=>$this->userinfo['comid'],'use.deleted_user'=>0])
                            ->where(['use.isturn'=>1,'use.status'=>0])
                            ->where(['list.certid'=>$vvv['certid']])
                            ->find();
                        if($exist){
                            $checkStatus = true;
                            $str .= "第".$kkk."行证书当前使用情况为空闲,但在流程申请中</br>";
                        }
                    }
               }else{
                   $checkStatus = true;
                   $str .= "第".$kkk."行证书当前使用情况为：".$statueuse_name."</br>";
               }
            }
            $str .= "是否继续？";
        }
        return outputJson(2000,lang('code_2000'), ['status'=>$checkStatus, 'data'=>$str]);
    }


    public function list_cert_use_bid(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['use.deleted_user','=','0'];
        $where[] = ['use.comid','=',$this->userinfo['comid']];
        $where[] = ['use.isturn','=',1];
        $where[] = ['use.status','in',[0,1]];


        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['use.chanid','=', $param['chanid']];
        }
        if(isset($param['flowuser']) && $param['flowuser'] != ''){
            $where[] = ['use.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['flowuser']) && $param['flowuser'] != ''){
            $where[] = ['use.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $created_at = explode(' - ', $param['created_at']);
            $st_at = $created_at[0].' 00:00:00';
            $end_at = $created_at[0].' 23:59:59';
            $where[] = ['use.created_at','between', [$st_at,$end_at]];
        }
        if(isset($param['enginid_name']) && $param['enginid_name'] != ''){
            $where[] = ['e.name','like', '%'.$param['enginid_name'].'%'];
        }

        if(isset($param['dt']) && !empty($param['dt'])){
            $where[] = ['use.dt','between', explode(' - ', $param['dt'])];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['use.status','=', $param['status']];
        }



        $data['chanid'] = (new UserService())->get_chaninfo_all();;
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';


        $data['data'] = CertUseBidModel::alias('use')
            ->leftJoin('bid e','e.id = use.bidid')
            ->field('use.*,e.name as engin_name')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_use_bid', 'bid'))
            ->order('use.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['num'] = CertUseBidListModel::where(['useid'=>$item['id']])->count();
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_use_bid');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function show_cert_use_bid(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = CertUseBidModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $engininfo = BidModel::where(['id'=>$data['data']['bidid']])->find();
        $data['engininfo'] = $engininfo;



        $list = CertUseBidListModel::where(['useid'=>$data['data']['id']])->select()->toArray();
        foreach ($list as &$item){
            $certInfo = CertModel::where(['id'=>$item['certid']])->find();
            $item['name'] = $certInfo['name'];
            $item['number'] = $certInfo['number'];
            $item['major_name'] = str_replace('[]', ',', $certInfo['major']);
            $item['person_name'] = CertPersonModel::where(['id'=>$certInfo['personid']])->value('name');
            $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($certInfo['statueuse']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($certInfo['chanid']);
            $item['opt_name'] = $item['opt'] > 0 ? '在用' : '停用';
        }
        $data['list'] = $list;

        $data['files'] = (new OptService())->get_file('cert_use_bid', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function down_cert_use_bid(Request $request)
    {
        if($this->request->isPost()){
            $id = $request->post('id',0,'int');
            $ids = $request->post('ids','','string');
            $ids = array_filter($ids);
            Db::startTrans();
            try {
                $useInfo = CertUseBidModel::where('id',$id)->find();
                $engin_name = BidModel::where(['id'=>$useInfo['bidid']])->value('name');
                $data = (new OptService())->down_watermark_zip($ids, '投标用证附件下载', $engin_name);

                (new OptService())->add_flow_log('下载', 'cert_use', $id);
                (new OptService())->add_log_list('下载', 'cert_use', $id, '投标用证');
                Db::commit();
                return outputJson(2000, lang('code_2000'),$data);
            } catch (\Exception $e){
                Db::rollback();
                return outputJson(4000, $e->getMessage());
            }
        }else{
            $id = $request->get('id',0,'int');
            $data = CertUseBidModel::where(['id'=>$id])->find();
            $certids_arr = CertUseBidListModel::where(['useid'=>$data['id']])->distinct(true)->column('certid');
            $personids = CertModel::where('id','in',$certids_arr)->distinct(true)->column('personid');

            $list = [];
            foreach ($personids as $pid) {
                $name = CertpersonModel::where('id',$pid)->value('name');
                $array = [
                    'name' => $name,
                    'len' => 0,
                    'children' => [],
                ];
                // 查询人员用证的证书
                $certIdArr = CertModel::where(['deleted_user'=>0,'personid'=>$pid])->column('id');
                foreach ($certIdArr as $certid){
                    if(in_array($certid,$certids_arr)){
                        $certArr['name'] = CertModel::where('id',$certid)->value('name');
                        // 查询证书的附件
                        $certArr['children'] = FileModel::where(['table'=>'cert','mid'=>$certid])->field('id,name')->select()->toArray();
                        $certArr['len'] = count($certArr['children']);
                        if(count($certArr['children']) == 0){
                            $array['len'] += 1;
                        }else{
                            $array['len'] += count($certArr['children']);
                        }
                        $array['children'][] = $certArr;
                    }
                }
                $array['len'] += 1;
                $list[] = $array;
            }

            return outputJson(2000,lang('code_2000'),$list);
        }
    }
    public function del_cert_use_bid(Request $request){
        $param = $request->post();
        $ids = array_filter(explode(',',$param['id']));
        if(count($ids) == 0){
            return outputJson(4000,'请选择需要删除的证书');
        }

        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = CertUseBidModel::where(['id'=>$id,'comid'=>$this->userinfo['comid']])->find();
                if(!$data){
                    continue;
                }
                CertUseBidModel::where(['id' => $data['id']])->update([
                    'deleted_user' => $this->userinfo['id'],
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
                (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_use_bid', $data['id'], '用证');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }



    public function count_cert_use_bid(Request $request){
        if($this->request->isPost()){
            $param = $request->post();
            get_page($param);

            $where[] = ['use.deleted_user','=','0'];
            $where[] = ['use.comid','=',$this->userinfo['comid']];
            $where[] = ['use.isturn','=',1];
            $where[] = ['use.status','=',1];
            $where[] = ['use.isreal','=',1];

            if(isset($param['engin_name']) && $param['engin_name'] != ''){
                $where[] = ['e.name','like', '%'.$param['engin_name'].'%'];
            }

            $place = CertModel::get_place();
            $data['data'] = CertUseBidModel::alias('use')
                ->leftJoin('bid e','e.id = use.bidid')
                ->field('use.*,e.state,e.status,e.isqi,e.business,e.name')
                ->where($where)
                ->where((new MenuService())->get_miss_where('cert_use_bid_count', 'bid'))
                ->order('e.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key)use ($place){
                    $item['business'] = $item['business'] == 1 ? '自营' : '联营';
                    $item['state'] = (new BidService())->get_bid_state_name_tag($item);

                    foreach ($place as $k => $v){
                        $certids = CertUseBidListModel::where(['useid'=>$item['id'],'place'=>$v])->distinct(true)->column('certid');
                        $item['place'.$k] = '';

                        $cert_data = CertModel::alias('cert')->field('cert.id,p.name')
                            ->leftJoin('cert_person p','p.id = cert.personid')
                            ->where('cert.id','in',$certids)
                            ->group('cert.id')
                            ->select();
                        foreach ($cert_data as $kk => $vv){
                            if($kk == 0){
                                $item['place'.$k] = '<span class="jumpcert" onclick="jump_cert('.$vv['id'].')">'.$vv['name'].'</span>';
                            }else{
                                $item['place'.$k] .= '，<span class="jumpcert" onclick="jump_cert('.$vv['id'].')">'.$vv['name'].'</span>';
                            }
                        }
                    }
                    return $item;
                })->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $col[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=>'left'];
            $col[] = ['field' => 'name', 'title' => '项目名称','event'=>'name','style'=>'color: #409EFF!important;cursor: pointer;'];
            $col[] = ['field' => 'business', 'title' => '项目属性'];
            $col[] = ['field' => 'state', 'title' => '项目状态'];
            $place = CertModel::get_place();
            foreach ($place as $k => $v){
                $col[] = ['field' => 'place'.$k, 'title' => $v];
            }
            $data['cols'] = $col;
            return outputJson(2000,lang('code_2000'),$data);
        }

    }
    public function count_cert_use_engin(Request $request){
        if($this->request->isPost()){
            $param = $request->post();
            get_page($param);

            $where[] = ['use.deleted_user','=','0'];
            $where[] = ['use.comid','=',$this->userinfo['comid']];
            $where[] = ['use.isturn','=',1];
            $where[] = ['use.status','=',1];
            $where[] = ['use.isreal','=',1];

            if(isset($param['engin_name']) && $param['engin_name'] != ''){
                $where[] = ['e.name','like', '%'.$param['engin_name'].'%'];
            }

            $place = CertModel::get_place();
            $data['data'] = CertUseModel::alias('use')
                ->leftJoin('engin e','e.id = use.enginid')
                ->field('use.*,e.state,e.business,e.name')
                ->where($where)
                ->where((new MenuService())->get_miss_where('cert_use_engin_count', 'e'))
                ->order('e.id DESC')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key)use ($place){
                    $item['business'] = $item['business'] == 1 ? '自营' : '联营';
                    $item['state'] = (new EnginService())->get_engin_state_name_tag($item['id'], $item['state']);

                    foreach ($place as $k => $v){
                        $certids = CertUseListModel::where(['useid'=>$item['id'],'place'=>$v])->distinct(true)->column('certid');
                        $item['place'.$k] = '';

                        $cert_data = CertModel::alias('cert')->field('cert.id,p.name')
                            ->leftJoin('cert_person p','p.id = cert.personid')
                            ->where('cert.id','in',$certids)
                            ->group('cert.id')
                            ->select();
                        foreach ($cert_data as $kk => $vv){
                            if($kk == 0){
                                $item['place'.$k] = '<span class="jumpcert" onclick="jump_cert('.$vv['id'].')">'.$vv['name'].'</span>';
                            }else{
                                $item['place'.$k] .= '，<span class="jumpcert" onclick="jump_cert('.$vv['id'].')">'.$vv['name'].'</span>';
                            }
                        }
                    }
                    return $item;
                })->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $col[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=>'left'];
            $col[] = ['field' => 'name', 'title' => '项目名称','event'=>'name','style'=>'color: #409EFF!important;cursor: pointer;'];
            $col[] = ['field' => 'business', 'title' => '项目属性'];
            $col[] = ['field' => 'state', 'title' => '项目状态'];
            $place = CertModel::get_place();
            foreach ($place as $k => $v){
                $col[] = ['field' => 'place'.$k, 'title' => $v];
            }
            $data['cols'] = $col;
            return outputJson(2000,lang('code_2000'),$data);
        }

    }
    public function show_cert_use_engin(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['business_name'] = $data['data']['business'] == 1 ? '自营' : '联营';
        $data['data']['state_name'] = (new EnginService())->get_engin_state_name($data['data']['id'], $data['data']['state']);
        $data['data']['man_xiang_name'] = UserModel::get_realname_by_pk($data['data']['man_xiang']);
        $data['data']['certfee'] = 0;


        $list = CertUseListModel::alias('list')
            ->field('list.*')
            ->join('cert_use use','use.id=list.useid')
            ->where(['use.comid'=>$this->userinfo['comid'],'use.deleted_user'=>0])
            ->where(['use.status'=>1,'use.isturn'=>1, 'use.enginid'=>$data['data']['id']])
            ->order('list.id ASC')
            ->select()->toArray();
        foreach ($list as &$vvv){
            $cert_data = CertModel::where('id', $vvv['certid'])->find();
            $vvv['cert_name'] = $cert_data['name'];
            $vvv['cert_number'] = $cert_data['number'];
            $vvv['cert_major'] = str_replace('[]', ',', $cert_data['major']);
            $vvv['person_name'] = CertPersonModel::where('id', $cert_data['personid'])->value('name');
            $vvv['statueuse_name'] = (new CertService())->get_cert_statueuse_name($cert_data['statueuse']);
            $vvv['com_name'] = DeptModel::get_name_by_pk($cert_data['chanid']);
            $vvv['months'] = (new ContractService())->get_cert_use_months($vvv['startdt'],$vvv['enddt']);
            $vvv['certfee'] = round($vvv['usefee']*$vvv['months'], 2);

            $data['data']['certfee'] += $vvv['certfee'];
        }
        $data['list'] = $list;
        return outputJson(2000,lang('code_2000'), $data);
    }



    /************************************ 借证 ************************************/
    public function list_cert_borrow(Request $request){
        $param = $request->post();
        get_page($param);
        $where[] = ['bw.deleted_user','=', 0];
        $where[] = ['bw.comid','=',$this->userinfo['comid']];
        $where[] = ['bw.isturn','=',1];
        $where[] = ['bw.status','in',[0,1]];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bw.yong|bw.explain','like','%'.$param['keyword'].'%'];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['bw.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['flowdept']) && !empty($param['flowdept'])){
            $where[] = ['bw.flowdept','like', '%'.$param['flowdept'].'%'];
        }
        if(isset($param['yong']) && !empty($param['yong'])){
            $where[] = ['bw.yong','like', '%'.$param['yong'].'%'];
        }
        if(isset($param['usedt']) && !empty($param['usedt'])){
            $where[] = ['bw.usedt','between', explode(' - ', $param['usedt'])];
        }
        if(isset($param['yudt']) && !empty($param['yudt'])){
            $where[] = ['bw.yudt','between', explode(' - ', $param['yudt'])];
        }
        if(isset($param['lingtype']) && !empty($param['lingtype'])){
            $where[] = ['bw.lingtype','=', $param['lingtype']];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['bw.state','=', $param['state']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bw.status','=', $param['status']];
        }

        $data['state'] = (new CertService())->get_cert_borrow_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['lingtype'] = (new CertService())->get_cert_borrow_lingtype();
        $data['is_lingtype'] = isset($param['lingtype']) ? $param['lingtype'] : '';

        $data['data'] = CertBorrowModel::alias('bw')
            ->field('bw.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_borrow', 'bw'))
            ->order('bw.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['state_name'] = (new CertService())->get_cert_borrow_state_name($item['state']);
                $item['lingtype_name'] = (new CertService())->get_cert_borrow_lingtype_name($item['lingtype']);
                $item['nums'] = CertBorrowListModel::where(['mid'=>$item['id']])->count();
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_borrow');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function mingxi_cert_borrow(Request $request){
        $param = $request->post();
        get_page($param);
        $where[] = ['bw.deleted_user','=', 0];
        $where[] = ['bw.comid','=',$this->userinfo['comid']];
        $where[] = ['bw.isturn','=',1];
        $where[] = ['bw.status','=',1];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bw.yong|bw.explain','like','%'.$param['keyword'].'%'];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['bw.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['yong']) && !empty($param['yong'])){
            $where[] = ['bw.yong','like', '%'.$param['yong'].'%'];
        }
        if(isset($param['state']) && $param['state'] != ''){
            $where[] = ['bw.state','=', $param['state']];
        }


        $data['state'] = (new CertService())->get_cert_borrow_state();
        $data['is_state'] = isset($param['state']) ? $param['state'] : '';

        $data['data'] = CertBorrowListModel::alias('list')
            ->field('bw.*,list.type,list.certid,list.guidt')
            ->join('cert_borrow bw','bw.id = list.mid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_borrow', 'bw'))
            ->order('bw.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $bill = FlowBillModel::where(['modenum'=>'cert_borrow','mid'=>$item['id']])->find();
                $item['sericnum'] = $bill['sericnum'];

                if($item['type'] == 1){
                    $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                    $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                    $item['number'] = $certinfo['number'];
                    $item['goes_name'] = (new CertService())->get_cert_goes_name($certinfo['goes']);
                    $item['cert_name'] = $certinfo['name'];
                    $item['person_name'] = $person['name'];
                }
                if($item['type'] == 2){
                    $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                    $item['number'] = $certinfo['number'];
                    $item['goes_name'] = (new CertService())->get_cert_company_goes_name($certinfo['goes']);
                    $item['cert_name'] = $certinfo['name'];
                    $item['person_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                }
                $item['state_name'] = (new CertService())->get_cert_borrow_state_name($item['state']);
                $item['lingtype_name'] = (new CertService())->get_cert_borrow_lingtype_name($item['lingtype']);
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function show_cert_borrow(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = CertBorrowModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['state_name'] = (new CertService())->get_cert_borrow_state_name($data['data']['state']);
        $data['data']['lingtype_name'] = (new CertService())->get_cert_borrow_lingtype_name($data['data']['lingtype']);

        $list = CertBorrowListModel::where(['mid'=>$data['data']['id']])->select()->toArray();
        foreach ($list as &$item){
            if($item['type'] == 1){
                $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                $item['major'] = str_replace('[]','，',$certinfo['major']);
                $item['major_name'] = str_replace('[]','，',$certinfo['major']);
                $item['number'] = $certinfo['number'];
                $item['form_name'] = (new CertService())->get_cert_form_name($certinfo['form']);
                $item['goes_name'] = (new CertService())->get_cert_goes_name($certinfo['goes']);
                $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                $item['name'] = $certinfo['name'].'-'.$person['name'];
            }
            if($item['type'] == 2){
                $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                $item['major'] = '';
                $item['major_name'] = '';
                $item['number'] = $certinfo['number'];
                $item['form_name'] = (new CertService())->get_cert_company_form_name($certinfo['form']);
                $item['goes_name'] = (new CertService())->get_cert_company_goes_name($certinfo['goes']);
                $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                $item['name'] = $certinfo['name'].'-'.$item['chanid_name'];
            }
        }
        $data['list'] = $list;


        $data['files'] = (new OptService())->get_file('cert_borrow', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function qu_cert_borrow(Request $request){
        if($request->isPost()){
            $param = $request->post();
            unset($param['token']);

            $param['state'] = 1;

            Db::startTrans();
            try {
                CertBorrowModel::update($param);


                (new OptService())->add_flow_log('取证', 'cert_borrow', $param['id']);
                (new OptService())->add_log_list('取证', 'cert_borrow', $param['id'], '借证申请');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = CertBorrowModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }
            $data['data']['qudt'] = date("Y-m-d");
            $data['data']['lingtype_name'] = (new CertService())->get_cert_borrow_lingtype_name($data['data']['lingtype']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function gui_cert_borrow(Request $request){
        if($request->isPost()){
            $param = $request->post();


            $list = array_filter($param['list']);
            unset($param['list']);

            Db::startTrans();
            try {
                foreach ($list as $item){
                    $old = CertBorrowListModel::where(['id'=>$item['id']])->find();
                    if(empty($old['guidt']) || $old['guidt'] == '0000-00-00'){
                        if($item['guidt']){
                            if($old['type'] == 1){
                                CertModel::where(['id'=>$old['certid']])->update(['goes'=>1]);
                            }else{
                                CertCompanyModel::where(['id'=>$old['certid']])->update(['goes'=>1]);
                            }
                        }
                    }else{
                        if(!$item['guidt']){
                            if($old['type'] == 1){
                                CertModel::where(['id'=>$old['certid']])->update(['goes'=>2]);
                            }else{
                                CertCompanyModel::where(['id'=>$old['certid']])->update(['goes'=>2]);
                            }
                        }
                    }
                    CertBorrowListModel::update($item);
                }


                $state = 2;
                $newList = CertBorrowListModel::where(['mid'=>$param['id']])->select()->toArray();
                foreach($newList as $vvv){
                    if(!$vvv['guidt'] || $vvv['guidt'] == '0000-00-00'){
                        $state = 1;
                    }
                }

                CertBorrowModel::where(['id'=>$param['id']])->update(['state'=>$state]);



                (new OptService())->add_flow_log('归还', 'cert_borrow', $param['id']);
                (new OptService())->add_log_list('归还', 'cert_borrow', $param['id'], '借证申请');

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = CertBorrowModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $list = CertBorrowListModel::where(['mid'=>$data['data']['id']])->select()->toArray();
            foreach ($list as &$item){
                if($item['type'] == 1){
                    $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                    $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                    $item['major'] = str_replace('[]','，',$certinfo['major']);
                    $item['number'] = $certinfo['number'];
                    $item['form_name'] = (new CertService())->get_cert_form_name($certinfo['form']);
                    $item['goes_name'] = (new CertService())->get_cert_goes_name($certinfo['goes']);
                    $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                    $item['name'] = $certinfo['name'].'-'.$person['name'];

                    $item['isedit'] = false;
                    if(empty($item['guidt']) || $item['guidt'] == '0000-00-00'){
                        $item['isedit'] = true;
                    }else{
                        if($certinfo['goes'] == 1){
                            $exist = CertBorrowListModel::alias('list')
                                ->join('cert_borrow bw','bw.id=list.mid')
                                ->where(['bw.comid'=>$this->userinfo['comid'],'bw.deleted_user'=>0])
                                ->where(['bw.isturn'=>1,'bw.status'=>0])
                                ->where(['list.type'=>1,'list.certid'=>$item['certid']])
                                ->where('bw.id','neq',$item['id'])
                                ->find();
                            if(!$exist){
                                $item['isedit'] = true;
                            }
                        }
                    }
                }
                if($item['type'] == 2){
                    $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                    $item['major'] = '';
                    $item['number'] = $certinfo['number'];
                    $item['form_name'] = (new CertService())->get_cert_company_form_name($certinfo['form']);
                    $item['goes_name'] = (new CertService())->get_cert_company_goes_name($certinfo['goes']);
                    $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                    $item['name'] = $certinfo['name'].'-'.$item['chanid_name'];
                    $item['isedit'] = false;
                    if(empty($item['guidt']) || $item['guidt'] == '0000-00-00'){
                        $item['isedit'] = true;
                    }else{
                        if($certinfo['goes'] == 1){
                            $exist = CertBorrowListModel::alias('list')
                                ->join('cert_borrow bw','bw.id=list.mid')
                                ->where(['bw.comid'=>$this->userinfo['comid'],'bw.deleted_user'=>0])
                                ->where(['bw.isturn'=>1,'bw.status'=>0])
                                ->where(['list.type'=>2,'list.certid'=>$item['certid']])
                                ->where('bw.id','neq',$item['id'])
                                ->find();
                            if(!$exist){
                                $item['isedit'] = true;
                            }
                        }
                    }
                }


            }
            $data['list'] = $list;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function down_cert_borrow(Request $request)
    {
        if($this->request->isPost()){
            $id = $request->post('id',0,'int');
            $ids = $request->post('ids','','string');
            $ids = array_filter($ids);
            Db::startTrans();
            try {
                $info = CertBorrowModel::where(['id'=>$id])->find();
                $data = (new OptService())->down_watermark_zip($ids, '借证申请附件下载', $info['yong']);
                (new OptService())->add_flow_log('下载电子件', 'cert_borrow', $id);
                (new OptService())->add_log_list('下载电子件', 'cert_borrow', $id, '借证申请');
                Db::commit();
                return outputJson(2000, lang('code_2000'),$data);
            } catch (\Exception $e){
                Db::rollback();
                return outputJson(4000, $e->getMessage());
            }
        }else{
            $id = $request->get('id',0,'int');
            $data = CertBorrowModel::where(['id'=>$id])->find();

            $list = [];
            $info = CertBorrowListModel::where(['mid'=>$data['id']])->order('type ASC')->select()->toArray();
            foreach ($info as $item){
                if($item['type'] == 1){
                    $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                    $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                    $name = $certinfo['name'].'-'.$person['name'];
                    $certFile = FileModel::where(['table'=>'cert','mid'=>$item['certid']])->field('id,name')->select()->toArray();
                    $personFile = FileModel::where(['table'=>'cert_person','mid'=>$certinfo['personid']])->field('id,name')->select()->toArray();
                    $children = array_merge($certFile, $personFile);
                }
                if($item['type'] == 2){
                    $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                    $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                    $name = $certinfo['name'].'-'.$item['chanid_name'];
                    $children = FileModel::where(['table'=>'cert_company','mid'=>$item['certid']])->field('id,name')->select()->toArray();
                }

                $list[] = [
                    'certid' => $certinfo['id'],
                    'name' => $name,
                    'children' => $children,
                ];
            }
            return outputJson(2000,lang('code_2000'),$list);
        }
    }

    public function list_cert_down(Request $request){
        $param = $request->post();
        get_page($param);
        $where[] = ['bw.deleted_user','=', 0];
        $where[] = ['bw.comid','=',$this->userinfo['comid']];
        $where[] = ['bw.isturn','=',1];
        $where[] = ['bw.status','in',[0,1]];

        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bw.yong|bw.explain','like','%'.$param['keyword'].'%'];
        }
        if(isset($param['flowuser']) && !empty($param['flowuser'])){
            $where[] = ['bw.flowuser','like', '%'.$param['flowuser'].'%'];
        }
        if(isset($param['flowdept']) && !empty($param['flowdept'])){
            $where[] = ['bw.flowdept','like', '%'.$param['flowdept'].'%'];
        }
        if(isset($param['yong']) && !empty($param['yong'])){
            $where[] = ['bw.yong','like', '%'.$param['yong'].'%'];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bw.status','=', $param['status']];
        }

        $data['data'] = CertDownModel::alias('bw')
            ->field('bw.*')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_down', 'bw'))
            ->order('bw.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['nums'] = CertDownListModel::where(['mid'=>$item['id']])->count();
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('cert_down');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function show_cert_down(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = CertDownModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $list = CertDownListModel::where(['mid'=>$data['data']['id']])->select()->toArray();
        foreach ($list as &$item){
            if($item['type'] == 1){
                $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                $item['major'] = str_replace('[]','，',$certinfo['major']);
                $item['number'] = $certinfo['number'];
                $item['form_name'] = (new CertService())->get_cert_form_name($certinfo['form']);
                $item['goes_name'] = (new CertService())->get_cert_goes_name($certinfo['goes']);
                $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                $item['name'] = $certinfo['name'].'-'.$person['name'];
            }
            if($item['type'] == 2){
                $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                $item['major'] = '';
                $item['number'] = $certinfo['number'];
                $item['form_name'] = (new CertService())->get_cert_company_form_name($certinfo['form']);
                $item['goes_name'] = (new CertService())->get_cert_company_goes_name($certinfo['goes']);
                $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                $item['name'] = $certinfo['name'].'-'.$item['chanid_name'];
            }
        }
        $data['list'] = $list;


        $data['files'] = (new OptService())->get_file('cert_down', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function down_cert_down(Request $request)
    {
        if($this->request->isPost()){
            $id = $request->post('id',0,'int');
            $ids = $request->post('ids','','string');
            $ids = array_filter($ids);
            Db::startTrans();
            try {
                $info = CertDownModel::where(['id'=>$id])->find();
                $data = (new OptService())->down_watermark_zip($ids, '证件下载申请附件下载', $info['yong']);
                (new OptService())->add_flow_log('下载电子件', 'cert_down', $id);
                (new OptService())->add_log_list('下载电子件', 'cert_down', $id, '证件下载申请');
                Db::commit();
                return outputJson(2000, lang('code_2000'),$data);
            } catch (\Exception $e){
                Db::rollback();
                return outputJson(4000, $e->getMessage());
            }
        }else{
            $id = $request->get('id',0,'int');
            $data = CertDownModel::where(['id'=>$id])->find();

            $list = [];
            $info = CertDownListModel::where(['mid'=>$data['id']])->order('type ASC')->select()->toArray();
            foreach ($info as $item){
                if($item['type'] == 1){
                    $certinfo = CertModel::where(['id'=>$item['certid']])->find();
                    $person = CertPersonModel::where(['id'=>$certinfo['personid']])->find();
                    $name = $certinfo['name'].'-'.$person['name'];
                    $certFile = FileModel::where(['table'=>'cert','mid'=>$item['certid']])->field('id,name')->select()->toArray();
                    $personFile = FileModel::where(['table'=>'cert_person','mid'=>$certinfo['personid']])->field('id,name')->select()->toArray();
                    $children = array_merge($certFile, $personFile);
                }
                if($item['type'] == 2){
                    $certinfo = CertCompanyModel::where(['id'=>$item['certid']])->find();
                    $item['chanid_name'] = DeptModel::get_name_by_pk($certinfo['chanid']);
                    $name = $certinfo['name'].'-'.$item['chanid_name'];
                    $children = FileModel::where(['table'=>'cert_company','mid'=>$item['certid']])->field('id,name')->select()->toArray();
                }

                $list[] = [
                    'certid' => $certinfo['id'],
                    'name' => $name,
                    'children' => $children,
                ];
            }
            return outputJson(2000,lang('code_2000'),$list);
        }
    }




    public function list_cert_matching()
    {
        if($this->request->isPost()){
            $input = input('post.');
            $list = input('post.list',[]);
            $list = array_filter($list);

            if($input['is_both'] == 0){
                return outputJson(2000,'没有查询到数据!',['data'=>[],'count'=>0]);
            }
            if(count($list) == 0){
                return outputJson(4000,'请填写条件');
            }

            $is_both = $input['is_both'];
            // 检查list
            $check_list = [];
            // 总数list
            $list_all = [];
            // 任意均可数据
            $list_data = [];

            // 查询所有人员
//            $cert_person_data = CertpersonModel::field('id,socstartdt,socenddt')->where(['deleted_user'=>0,
//                'comid'=>$this->userinfo['comid'],'state'=>'在职'])->select();

            foreach ($list as $k=>$item){
                // 数据list
                $list = [];
                // 判断重复的list
                $repeat_list = [];

                $where = [];
                $where[] = ['c.comid','=',$this->userinfo['comid']];
                $where[] = ['c.deleted_user','=','0'];
                $where[] = ['c.state','not in','2,3'];
                $item = json_decode($item,true);

                // 分类
                if(isset($item['type']) && !empty($item['type'])){
                    // 查询子分类
                    $topid = OptionModel::where(['comid'=>$this->userinfo['comid'],'num'=>'cert_type','deleted_user'=>0])->value('id');
                    $id = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$topid,'keyid'=>$item['type'],'deleted_user'=>0])->value('id');
                    $ids = (new OptService())->get_option_ids($id);
                    $ids[] = $item['type'];
                    $where[] = ['c.type','in', $ids];
                }
                // 证书名称
                if(isset($item['name']) && !empty($item['name'])){
                    $where[] = ['c.name','in',$item['name']];
                }
                // 专业
                if(isset($item['major']) && !empty($item['major'])){
                    $majorArr[] = 'c.major';
                    foreach($item['major'] as $v){
                        $majorArr[] = ['like','%'.$v.'%'];
                    }
                    $majorArr[] = 'or';
                    $where[] = $majorArr;
                }
                // 学历
                if(isset($item['xueli']) && !empty($item['xueli'])){
                    $where[] = ['p.xueli','in',$item['xueli']];
                }
                // 社保
                if(isset($item['social']) && !empty($item['social'])){
                    $where[] = ['p.social','in',$item['social']];
                }
                // 人员性质
                if(isset($item['nature']) && !empty($item['nature'])){
                    $where[] = ['p.nature','=',$item['nature']];
                }
                // 证书去向
                if(isset($item['goes']) && !empty($item['goes'])){
                    $where[] = ['c.goes','=',$item['goes']];
                }
                // 使用情况
                if(isset($item['statueuse']) && !empty($item['statueuse'])){
                    $where[] = ['c.statueuse','in',$item['statueuse']];
                }

                // 所属单位
                if(isset($item['chanid']) && !empty($item['chanid'])){
                    $chanid = DeptModel::where(['deleted_user'=>0,'status'=>1,'pid'=>$item['chanid']])->column('id');
                    $chanid[] = $item['chanid'];
                    $where[] = ['c.chanid','in',$chanid];
                    // $where[] = ['c.chanid','=',$item['chanid']];
                }

                // 月份数查询
                // $where_person_ids = [];
                // foreach ($cert_person_data as $v){
                //     if($item['month'] > 0){
                //         // 社保购买月份数
                //         if(!empty($v['socstartdt']) && $v['socstartdt'] != '0000-00-00'){
                //             if(!empty($item['socenddt']) && $v['socenddt'] != '0000-00-00'){
                //                 $enddt = $item['socenddt'];
                //             }else{
                //                 $enddt = date('Y-m-d');
                //             }
                //             list($y1,$m1) = explode('-',$v['socstartdt']);
                //             list($y2,$m2) = explode('-',$enddt);
                //             $social_num = ($y2 - $y1) * 12 + ($m2 - $m1) + 1;
                //         }else{
                //             $social_num = 0;
                //         }
                //         if($item['month'] == 1 && $social_num > 3){ // 大于3个月
                //             $where_person_ids[] = $v['id'];
                //         }else if($item['month'] == 2 && $social_num > 6){ // 大于6个月
                //             $where_person_ids[] = $v['id'];
                //         }else if($item['month'] == 3 && $social_num > 12){ // 大于12个月
                //             $where_person_ids[] = $v['id'];
                //         }
                //     }else{
                //         $where_person_ids[] = $v['id'];
                //     }
                // }


                // 数量限制查询 持证人，证书名称，证书编号，有效期限，证书专业，证书状态，证书去向，社保状态
                $site_manager = CertModel::alias('c')->field('c.id,c.personid,c.name as cert_name,c.number,c.expiry_dt,c.issue_unit,
                c.major,c.chanid,c.state,c.goes,p.name as person_name,p.social,p.nature,p.state as person_state')
                    ->leftJoin('cert_person p','p.id = c.personid')
                    ->where($where)
                    ->group('c.id')->order('p.id desc')->select()->toArray();

                foreach ($site_manager as $v){
                    $list[] = $v;
                    $list_data[] = $v;
                }
                if($is_both == 1){
                    $cont_manager = CertModel::alias('c')->field('c.id,c.personid,c.name as cert_name,c.number,c.expiry_dt,c.issue_unit,
                    c.major,c.chanid,c.state,c.goes,p.name as person_name,p.social,p.nature,p.state as person_state')
                        ->leftJoin('cert_person p','p.id = c.personid')
                        ->where($where)
                        ->group('c.id')->select()->toArray();
                    foreach($cont_manager as $v){
                        array_push($list_all,$v);
                    }
                }

                // 同时兼备处理
                if($is_both == 2){
                    if($k == 1){ // 第一次赋值
                        $check_list = $list;
                        continue;
                    }else{
                        for($i=0;$i<count($check_list);$i++){
                            for($j=0;$j<count($list);$j++){
                                if($check_list[$i]['personid'] == $list[$j]['personid']){
                                    array_push($repeat_list,$check_list[$i]);
                                    array_push($repeat_list,$list[$j]);
                                }
                            }
                        }
                        $check_list = $repeat_list;
                    }
                } // 判断同时具备结束
            }// 结束全部判断 输入list集合


            // 同时兼备处理
            if($is_both == 2){
                $res = [];
                foreach ($check_list as $value) {
                    //查看有没有重复项
                    if(isset($res[$value['personid'].'-'.$value['id']])){
                        //有：销毁
                        unset($value);
                    }else{
                        $res[$value['personid'].'-'.$value['id']] = $value;
                    }
                }
                $list = array_values($res);
            }else{
                $list = $list_data;
            }

            // 数据返回
            if(count($list) == 0){
                return outputJson(2000,'没有查询到数据!',['data'=>[],'count'=>0]);
            }else{
                if($is_both == 1){ // 任意均可
                    $list_all = array_unique($list_all,SORT_REGULAR);
                    $count = count($list_all);
                }else{ // 同时具备
                    $count = count($list);
                }
                $list = array_unique($list,SORT_REGULAR);
                foreach ($list as &$item){
                    $item['nature'] = (new OptService())->get_base_showname('person_nature',$item['nature']);
                    // 归属公司
                    $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
                    // 有效期处理
                    $expiry_dtArr = explode('[]',$item['expiry_dt']);
                    $arr = [];
                    foreach($expiry_dtArr as $v){
                        if(empty($v)){
                            $arr[] = $v;
                        }else{
                            if($v < date('Y-m-d')){
                                $arr[] = '<span style="color:red;">'.$v.'</span>';
                            }else{
                                $arr[] = $v;
                            }
                        }
                    }
                    $item['expiry_dt'] = implode('<br/>',$arr);
                    // 专业处理
                    if(!empty(explode('[]',$item['major']))){
                        $item['major'] = str_replace('[]','<br/>',$item['major']);
                    }else{
                        $item['major'] = '';
                    }
                    // 社保状态
                    $item['social'] = (new OptService())->get_base_showname('person_social',$item['social']);
                    // 证书状态
                    $cert_state = (new CertService())->get_cert_state();
                    $item['state'] = isset($cert_state[$item['state']])?$cert_state[$item['state']]:'';
                    // 证书去向
                    $cert_goes = (new CertService())->get_cert_goes();
                    $item['goes'] = isset($cert_goes[$item['goes']])?$cert_goes[$item['goes']]:'';
                }
                $success_arr = ['data'=>$list,'count'=>$count];
                return outputJson(2000,lang('code_2000'),$success_arr);
            }
        }else{
            $data['sex'] = ['男','女'];
            $data['nature'] = (new OptService())->get_base_info('person_nature');
            $data['xueli'] = (new OptService())->get_base_info('person_xueli');
            //所属单位
            $data['chanid'] = DeptModel::where(['deleted_user'=>0,'status'=>1,'type'=>2])->field('id,name')->select()->toArray();
            $data['social'] = (new OptService())->get_base_info('person_social');
            $data['month'] = [1=>'大于3个月',2=>'大于6个月',3=>'大于9个月'];
            $data['type'] = (new OptService())->get_base_info('cert_type');
            $data['goes'] = (new CertService())->get_cert_goes();
            $data['state'] = (new CertService())->get_cert_state();
            $data['statueuse'] = (new CertService())->get_cert_statueuse();

            $flow = FlowClassModel::where(['comid'=>$this->userinfo['comid'],'setid'=>2,'status'=>1])->find();
            if($flow){
                $data['flow'] = 1;
            }else{
                $data['flow'] = 0;
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function cert_matching_alloc()
    {
        // 证书id
        $idArr = input('post.idArr');

        $data = CertModel::alias('c')
            ->field('p.name as person_name,p.nature as person_nature,c.name,c.major,c.number,c.chanid,c.state as cert_state,
                c.id,e.iszhu')
            ->leftJoin('cert_person p','p.id = c.personid')
            ->leftJoin('cert_employ e','p.id = e.personid')
            ->where('c.id','in',$idArr)
            ->select();
        $cert_state = (new CertService())->get_cert_state();
        $iszhu = CertEmployModel::get_iszhu();
        foreach ($data as &$item){
            $item['major'] = str_replace('[]','|',$item['major']);
            $item['chanid_name'] = DeptModel::get_name_by_pk($item['chanid']);
            $item['cert_state'] = isset($cert_state[$item['cert_state']])?$cert_state[$item['cert_state']]:'';
            $item['iszhu'] = isset($iszhu[$item['iszhu']])?$iszhu[$item['iszhu']]:'';
            $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
        }
        return outputJson(2000,lang('code_2000'),$data);
    }


    
    public function list_cert_form()
    {
        if($this->request->isPost()){
            $input = input('post.');
            get_page($input);

            // 查询条件
            $where[] = ['f.comid','=',$this->userinfo['comid']];
            $where[] = ['f.deleted_user','=','0'];
            if(isset($input['cert_type']) && !empty($input['cert_type'])){
                $where[] = ['f.cert_type','=',$input['cert_type']];
            }
            if(isset($input['cert_name']) && !empty($input['cert_name'])){
                $where[] = ['f.cert_name','=',$input['cert_name']];
            }

            $person_nature = (new OptService())->get_base_info('person_nature');
            $data['data'] = CertFormModel::alias('f')
                ->where($where)
                ->where((new MenuService())->get_miss_where('cert_form', 'f'))
                ->paginate($input['pagesize'],false,['page'=>$input['page']])
                ->each(function ($item,$key)use($person_nature){
                    // 查询所有证书信息
                    $topid = OptionModel::where(['comid'=>$this->userinfo['comid'],'num'=>'cert_type','deleted_user'=>0])->value('id');
                    $id = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$topid,'keyid'=>$item['cert_type'],'deleted_user'=>0])->value('id');
                    $typeids = (new OptService())->get_option_ids($id);
                    $typeids[] = $item['cert_type'];


                    $cert_data = CertModel::alias('cert')
                        ->field('cert.id,cert.state as cert_state,p.nature as person_nature')
                        ->leftJoin('cert_person p','p.id = cert.personid')
                        ->where(['cert.deleted_user'=>0,'cert.name'=>$item['cert_name'],
                            'cert.comid'=>$this->userinfo['comid'],'p.deleted_user'=>0])
                        ->where('cert.type','in',$typeids)
                        ->where('cert.major','like','%'.$item['cert_major'].'%')
                        ->group('cert.id')
                        ->select();


                    foreach ($person_nature as $v){
                        $item['num'.$v['value']] = 0;
                    }

                    $item['all_num'] = count($cert_data);
                    // $item['quan_num'] = $item['wai_num'] = $item['wei_num'] = 0;
                    $item['bao_kong'] = $item['bao_tou'] = $item['bao_jian'] = $item['bao_jiansuo'] = 0;
                    foreach ($cert_data as $v){
                        $item['num'.$v['person_nature']] += 1;

                        // $v['person_nature'] = (new OptService())->get_base_showname('person_nature',$v['person_nature']);
                        // // 现有数量 合计 全职 外聘 未知
                        // switch ($v['person_nature']){
                        //     case '全职': $item['quan_num'] += 1; break;
                        //     case '外聘': $item['wai_num'] += 1; break;
                        //     case '未知': $item['wei_num'] += 1; break;
                        // }


                        switch ($v['cert_state']){
                            case 1: $item['bao_kong'] += 1; break;
                            case 3: $item['bao_tou'] += 1; break;
                            case 5: $item['bao_jian'] += 1; break;
                            case 7: $item['bao_jiansuo'] += 1; break;
                        }
                    }
                    // 空缺数量
                    $item['free_num'] = ($item['num'] - $item['all_num']) > 0 ? $item['num'] - $item['all_num'] : 0;
                    $item['cert_type_name'] = (new OptService())->get_base_showname('cert_type',$item['cert_type']);
                    return $item;
                })->toArray();

            $data['cert_type'] = (new OptService())->get_base_info('cert_type');
            $data['butauth'] = (new MenuService())->get_butauth('cert_form');
            $data['person_nature'] = $person_nature;


            $count_where[] = ['comid','=',$this->userinfo['comid']];
            $count_where[] = ['deleted_user','=','0'];
            $count_where[] = ['state','not in','2,3'];
            // 企业主要人员状况
            // 建造师
            $count_arr['jzs_all'] = CertModel::where($count_where)->where('name','like','%建造师%')->count();
            // 一级建造师
            $count_arr['jzs_yiji'] = CertModel::where($count_where)->where(function ($query){
                $query->where('name','=','一级建造师')->whereOr('name','=','一级注册建造师')->whereOr('name','=','注册一级建造师');
            })->count();
            // 二级建造师
            $count_arr['jzs_erji'] = CertModel::where($count_where)->where(function ($query){
                $query->where('name','=','二级建造师')->whereOr('name','=','二级注册建造师')->whereOr('name','=','注册二级建造师');
            })->count();
            // 现场管理
            $count_arr['xcgl_shiyong'] = CertModel::where($count_where)->where('name','like','%施工员%')->count();
            $count_arr['xcgl_anquan']= CertModel::where($count_where)->where('name','like','%安全员%')->count();
            $count_arr['xcgl_cailiao'] = CertModel::where($count_where)->where('name','like','%材料员%')->count();
            $count_arr['xcgl_celiang'] = CertModel::where($count_where)->where('name','like','%测量员%')->count();
            $count_arr['xcgl_shiya'] = CertModel::where($count_where)->where('name','like','%试验员%')->count();
            $count_arr['xcgl_yusuan'] = CertModel::where($count_where)->where('name','like','%监理员%')->count();
            $count_arr['xcgl_zhiliang'] = CertModel::where($count_where)->where('name','like','%质量员%')->count();
            $count_arr['xcgl_zaojia'] = CertModel::where($count_where)->where('name','like','%造价员%')->count();
            $count_arr['xcgl_ziliao'] = CertModel::where($count_where)->where('name','like','%资料员%')->count();
            $count_arr['xcgl_jixie'] = CertModel::where($count_where)->where('name','like','%机械员%')->count();
            $count_arr['xcgl_laowu'] = CertModel::where($count_where)->where('name','like','%劳务员%')->count();
            $count_arr['xcgl_biaozhun'] = CertModel::where($count_where)->where('name','like','%标准员%')->count();
            $count_arr['xcgl_all'] = $count_arr['xcgl_shiyong']+$count_arr['xcgl_anquan']+$count_arr['xcgl_zaojia']+$count_arr['xcgl_zhiliang']
                +$count_arr['xcgl_laowu']+$count_arr['xcgl_celiang']+$count_arr['xcgl_jixie']+$count_arr['xcgl_shiya']+$count_arr['xcgl_ziliao']
                +$count_arr['xcgl_biaozhun']+$count_arr['xcgl_cailiao']+$count_arr['xcgl_yusuan'];
            // 技术工人
            $count_arr['js_chuji'] = CertModel::where($count_where)->where('major','like','%初级工%')->count();
            $count_arr['js_zhongji'] = CertModel::where($count_where)->where('major','like','%中级工%')->count();
            $count_arr['js_gaoji'] = CertModel::where($count_where)->where('major','like','%高级工%')->count();
            $count_arr['js_jishi'] = CertModel::where($count_where)->where('major','like','%技师%')->count();
            $count_arr['js_gaojijishi'] = CertModel::where($count_where)->where('major','like','%高级技师%')->count();
            $count_arr['js_all'] = $count_arr['js_chuji']+$count_arr['js_zhongji']+$count_arr['js_gaoji']+$count_arr['js_jishi']+$count_arr['js_gaojijishi'];
            $count_arr['js_gao_all'] =$count_arr['js_zhongji']+$count_arr['js_gaoji']+$count_arr['js_jishi']+$count_arr['js_gaojijishi'];

            // 三类人员证
            $count_arr['san_jiana'] = CertModel::where($count_where)->where('name','like','%建安A证%')->count();
            $count_arr['san_jianb'] = CertModel::where($count_where)->where('name','like','%建安B证%')->count();
            $count_arr['san_jianc'] = CertModel::where($count_where)->where('name','like','%建安C证%')->count();
            $count_arr['san_shuia'] = CertModel::where($count_where)->where('name','like','%水安A%')->count();
            $count_arr['san_shuib'] = CertModel::where($count_where)->where('name','like','%水安B%')->count();
            $count_arr['san_shuic'] = CertModel::where($count_where)->where('name','like','%水安C%')->count();
            $count_arr['san_all'] = $count_arr['san_jiana']+$count_arr['san_jianb']+$count_arr['san_jianc']+$count_arr['san_shuia']+
                $count_arr['san_shuib']+$count_arr['san_shuic'];
            $data['count_arr'] = $count_arr;
            return outputJson(2000,lang('code_2000'),$data);
        }else{
            $person_nature = (new OptService())->get_base_info('person_nature');

            $col[] = ['type' => 'checkbox', 'fixed' => 'left', 'rowspan'=> 2];
            $col[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=> 'left', 'rowspan'=> 2];
            $col[] = ['field' => 'cert_type_name', 'title' => '证书分类', 'width'=> 150, 'rowspan'=> 2];
            $col[] = ['field' => 'cert_name', 'title' => '证书名称', 'width'=> 150, 'rowspan'=> 2];
            $col[] = ['field' => 'cert_major', 'title' => '证书专业', 'width'=> 150, 'rowspan'=> 2];
            $col[] = ['field' => 'num', 'title' => '编制数量', 'width'=> 100, 'rowspan'=> 2];
            $col[] = ['field' => '', 'title' => '现有数量', 'width'=> 100, 'colspan'=> count($person_nature) + 1, 'align' => 'center'];
            $col[] = ['field' => 'free_num', 'title' => '空缺数量', 'width'=> 100, 'rowspan'=> 2];
            $col[] = ['field' => '', 'title' => '使用情况', 'width'=> 100, 'colspan'=> 5, 'align' => 'center'];
            $col[] = ['field' => 'explain', 'title' => '备注', 'minWidth'=> 150, 'rowspan'=> 2];
            $data[] = $col;

            $cols = [];
            $cols[] = ['field' => 'all_num', 'title' => '合计', 'width'=> 100, 'event' => 'all_num', 'style'=>'color: #409EFF!important;cursor: pointer;'];
            foreach ($person_nature as $item){
                $cols[] = ['field' => 'num'.$item['value'], 'title' => $item['title'], 'width'=> 100, 'event' => 'num'.$item['value'], 'style'=>'color: #409EFF!important;cursor: pointer;'];
            }
            // 1 => '空闲',
            //            2 => '用证申请中',
            //            3 => '投标在用',
            //            4 => '报建在用',
            //            5 => '报建在用(锁证)',



            $cols[] = ['field' => 'bao_kong', 'title' => '空闲', 'width'=> 100];
            $cols[] = ['field' => 'bao_tou', 'title' => '投标在用', 'width'=> 100];
            $cols[] = ['field' => 'bao_jian', 'title' => '报建在用', 'width'=> 100];
            $cols[] = ['field' => 'bao_jiansuo', 'title' => '报建在用(锁证)', 'width'=> 100];
            $data[] = $cols;

            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function add_cert_form()
    {
        if ($this->request->isPost()){
            $input = input('post.');
            $check_validate = $this->validate($input,'CertForm.add');
            if($check_validate !== true){
                return outputJson(4009,$check_validate);
            }

            // 判断是否有相同的证书分类和证书名称
            if(empty($input['cert_major'])){
                $check_data = CertformModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid'],'cert_type'=>$input['cert_type'],
                    'cert_name'=>$input['cert_name']])->find();
                if($check_data){
                    return outputJson(4000,'证书分类和名称已存在请勿重复添加');
                }
            }else{
                $check_data = CertformModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid'],'cert_type'=>$input['cert_type'],
                    'cert_name'=>$input['cert_name'],'cert_major'=>$input['cert_major']])->find();
                if($check_data){
                    return outputJson(4000,'该证书专业已存在请勿重复添加');
                }
            }


            $input['comid'] = $this->userinfo['comid'];
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();
            $input['created_user'] = $this->userinfo['id'];
            $input['created_at'] = date('Y-m-d H:i:s');
            Db::startTrans();
            try{
                $result = CertformModel::create($input);

                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'cert_from', $result->id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'cert_from', $result->id, '编制');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['cert_type'] = (new OptService())->get_base_info('cert_type');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function edit_cert_form()
    {
        if($this->request->isPost()){
            $input = input('post.');
            unset($input['token']);
            $check_validate = $this->validate($input,'CertForm.edit');
            if($check_validate !== true){
                return outputJson(4009,$check_validate);
            }

            // 判断是否有相同的证书分类和证书名称
            if(empty($input['cert_major'])){
                $check_data = CertformModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid'],'cert_type'=>$input['cert_type'],
                    'cert_name'=>$input['cert_name']])->where('id','<>',$input['id'])->find();
                if($check_data){
                    return outputJson(4000,'证书分类和名称已存在请勿重复添加');
                }
            }else{
                $check_data = CertformModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid'],'cert_type'=>$input['cert_type'],
                    'cert_name'=>$input['cert_name'],'cert_major'=>$input['cert_major']])->where('id','<>',$input['id'])->find();
                if($check_data){
                    return outputJson(4000,'该证书专业已存在请勿重复添加');
                }
            }


            $input['updated_user'] = $this->userinfo['id'];
            $input['updated_at'] = date('Y-m-d H:i:s');
            Db::startTrans();
            try{
                CertformModel::update($input);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'cert_form', $input['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'cert_form', $input['id'], '编制');
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = input('get.id',0);
            $result = CertformModel::where(['comid'=>$this->userinfo['comid'],'id'=>$id])->find();
            if(!$result){
                return outputJson(4000,lang('code_4000'));
            }
            $data['data'] = $result;
            $data['cert_type'] = (new OptService())->get_base_info('cert_type');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_cert_form()
    {
        $id = input('post.id',0);
        $data = CertformModel::where(['id'=>$id])->find();
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }
        Db::startTrans();
        try{
            CertformModel::where(['id'=>$data['id']])->update([
                'deleted_at' => date('Y-m-d H:i:s'),
                'deleted_user' => $this->userinfo['id'],
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'cert_form', $data['id'], '编制');
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    // 获取证书名称
    public function get_cert_name_list()
    {
        $type = input('get.type','');
        $data = CertModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'type'=>$type])
            ->where('state','not in','2,3')->distinct(true)->column('name');
        return outputJson(2000,lang('code_2000'),$data);
    }

    // 获取证书专业
    public function get_cert_major_list()
    {
        $type = input('get.type','');
        $name = input('get.name','');
        $majorArr = CertModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'type'=>$type])
            ->where('name','in',$name)
            ->where('state','not in','2,3')
            ->distinct(true)->column('major');

        $data = [];
        foreach ($majorArr as $v){
            $arr = explode('[]',$v);
            $data = array_merge($data,$arr);
        }
        $data = array_unique(array_filter($data));
        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_cert_census(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['p.deleted_user','=','0'];
        $where[] = ['p.comid','=',$this->userinfo['comid']];


        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['p.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['sex']) && !empty($param['sex'])){
            $where[] = ['p.sex','=', $param['sex']];
        }
        if(isset($param['idcard']) && !empty($param['idcard'])){
            $where[] = ['p.idcard','like', '%'.$param['idcard'].'%'];
        }
        if(isset($param['nature']) && !empty($param['nature'])){
            $where[] = ['p.nature','=', $param['nature']];
        }
        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['p.chanid','=', $param['chanid']];
        }
        if(isset($param['state']) && !empty($param['state'])){
            $where[] = ['p.state','=', $param['state']];
        }
        if(isset($param['social']) && !empty($param['social'])){
            $where[] = ['p.social','=', $param['social']];
        }
        if(isset($param['socialareas']) && !empty($param['socialareas'])){
            $where[] = ['p.socialareas','like', '%'.$param['socialareas'].'%'];
        }

        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['e.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['start_dt']) && !empty($param['start_dt'])){
            $where[] = ['e.start_dt','between', explode(' - ',$param['start_dt'])];
        }
        if(isset($param['end_dt']) && !empty($param['end_dt'])){
            $where[] = ['e.end_dt','between', explode(' - ',$param['end_dt'])];
        }
        if(isset($param['qualification']) && !empty($param['qualification'])){
            $where[] = ['e.qualification','like','%'.$param['qualification'].'%'];
        }
        if(isset($param['iszhu']) && !empty($param['iszhu'])){
            $where[] = ['e.iszhu','eq',$param['iszhu']];
        }
        if(isset($param['purpose']) && !empty($param['purpose'])){
            $where[] = ['e.purpose','eq',$param['purpose']];
        }
        if(isset($param['pay_type']) && !empty($param['pay_type'])){
            $where[] = ['e.pay_type','eq',$param['pay_type']];
        }

        if(isset($param['cert_name']) && !empty($param['cert_name'])){
            $where[] = ['c.name','like', '%'.$param['cert_name'].'%'];
        }
        if(isset($param['cert_major']) && !empty($param['cert_major'])){
            $where[] = ['c.major','like', '%'.$param['cert_major'].'%'];
        }
        if(isset($param['expiry_dt']) && !empty($param['expiry_dt'])){
            $expiry_dt = explode(' - ', $param['expiry_dt']);
            $ids = [];
            $c_data = CertModel::where(['deleted_user'=>0])->field('id,expiry_dt')->select();
            foreach ($c_data as $item){
                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                if($expiry_dtArr){
                    foreach ($expiry_dtArr as $dt){
                        if($dt >= $expiry_dt[0] && $dt <= $expiry_dt[1]){
                            $ids[] = $item['id'];
                        }
                    }
                }
            }
            $ids = array_unique($ids);
            $where[] = ['c.id','in',$ids];
        }
        if(isset($param['cert_state']) && !empty($param['cert_state'])){
            $where[] = ['c.state','=', $param['cert_state']];
        }


        $iszhu = CertEmployModel::get_iszhu();
        $pay_type = CertEmployModel::get_pay_type();
        $state = ['在职','离职'];
        $data['data'] = CertPersonModel::alias('p')->field('p.*,p.state as person_state')
            ->leftJoin('cert c','p.id = c.personid')
            ->leftJoin('cert_employ e','p.id = e.personid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert_census', 'p'))
            ->order('p.id desc')
            ->group('p.id')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key)use ($iszhu,$state,$pay_type){
                $item['age'] = (new CertService())->get_age_by_idcard($item['idcard']);
                // 判断聘期是否在当前时间内
                $date = date('Y-m-d');
                $employ = CertEmployModel::where(['deleted_user'=>0,'personid'=>$item['id']])->where('start_dt','elt',$date)
                    ->where('end_dt','egt',$date)->find();
                if(!$employ){
                    $employ = CertEmployModel::where(['deleted_user'=>0,'personid'=>$item['id']])->order('end_dt desc')->find();
                }
                $item['number'] = '';
                if($employ){
                    $item['start_dt'] = $employ['start_dt'];
                    $item['end_dt'] = $employ['end_dt'];
                    $item['number'] = $employ['number'];
                    $item['employid'] = $employ['id'];

                    $qualification = array_filter(explode(',',$employ['qualification']));
                    $qualificationArr = [];
                    foreach($qualification as $vv){
                        $qualificationArr[] = (new OptService())->get_base_showname('cert_employ_qualification',$vv);
                    }
                    $item['qualification'] = implode(',',$qualificationArr);

                    $item['purpose'] = (new OptService())->get_base_showname('cert_employ_purpose',$employ['purpose']);
                    $item['iszhu'] = isset($iszhu[$employ['iszhu']]) ? $iszhu[$employ['iszhu']] : '';
                    $item['pay_type'] = isset($pay_type[$employ['pay_type']]) ? $pay_type[$employ['pay_type']] : '';
                    $item['money'] = $employ['money'];
                }
                $item['xueli'] = (new OptService())->get_base_showname('person_xueli',$item['xueli']);
                $item['nature'] = (new OptService())->get_base_showname('person_nature',$item['nature']);
                $item['chan_name'] = DeptModel::get_name_by_pk($item['chanid']);
                $item['social'] = (new OptService())->get_base_showname('person_social',$item['social']);
                if(empty($item['socstartdt']) || $item['socstartdt'] == '0000-00-00'){
                    $item['month'] = 0;
                }else{
                    if(empty($item['socenddt']) || $item['socenddt'] == '0000-00-00'){
                        $socenddt = date('Y-m-d');
                    }else{
                        $socenddt = $item['socenddt'];
                    }
                    list($y1,$m1) = explode('-',$item['socstartdt']);
                    list($y2,$m2) = explode('-',$socenddt);
                    $item['month'] = ($y2 - $y1) * 12 + ($m2 - $m1) + 1;
                }
            })
            ->toArray();

        $old_data = $data['data']['data'];

        $list = [];
        // 查询证书信息
        $state = (new CertService())->get_cert_state();
        foreach ($old_data as $item){
            $cert_data = CertModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid'],'personid'=>$item['id']])->where('state','not in','2,3')
                ->select()->toArray();
            if(count($cert_data) > 0){
                foreach ($cert_data as $v){
                    $item['certid'] = $v['id'];
                    $item['cert_name'] = $v['name'];
                    $item['cert_major'] = str_replace('[]','<br/>',$v['major']);
                    $item['cert_number'] = $v['number'];
                    $item['cert_expiry_dt'] = str_replace('[]','<br/>',$v['expiry_dt']);
                    $item['cert_state'] = isset($state[$v['state']]) ? $state[$v['state']] : '';
                    // 投标在用项目
                    $enginArr = (new CertService())->get_cert_use_bid($v['id']);
                    if(count($enginArr) > 0){
                        $nameArr = array_column($enginArr,'name');
                        $item['bid_name'] = implode('<br/>',$nameArr);
                    }else{
                        $item['bid_name'] = '';
                    }
                    // 报建在用项目
                    $enginArr = (new CertService())->get_cert_use_engin($v['id']);
                    if(count($enginArr) > 0){
                        $nameArr = array_column($enginArr,'name');
                        $item['engin_name'] = implode('<br/>',$nameArr);
                    }else{
                        $item['engin_name'] = '';
                    }
                    $list[] = $item;
                }
            }else{
                $item['cert_name'] = '';
                $item['cert_major'] = '';
                $item['cert_number'] = '';
                $item['cert_expiry_dt'] = '';
                $item['cert_state'] = '';
                $item['bid_name'] = '';
                $item['engin_name'] = '';
                $list[] = $item;
            }
        }
        $data['data']['data'] = $list;

        $data['iszhu'] = $iszhu;
        $data['channel'] = (new OptService())->get_base_info('cert_employ_channel');
        $data['qualification'] = (new OptService())->get_base_info('cert_employ_qualification');
        $data['purpose'] = (new OptService())->get_base_info('cert_employ_purpose');
        $data['pay_type'] = CertEmployModel::get_pay_type();

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['social'] = (new OptService())->get_base_info('person_social');
        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['state'] = ['在职','离职'];

        $data['cert_status'] = (new CertService())->get_cert_state();
        $data['areas_options'] = (new OptService())->get_city_cader();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function cert_count_shi(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];

        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['person.chanid','=',$param['chanid']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['cert.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['cert.number','like', '%'.$param['number'].'%'];
        }

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['is_nature'] = isset($param['nature']) ? $param['nature'] : '';

        $data['data'] = CertModel::alias('cert')
            ->field('cert.*,person.name as person_name,person.chanid as person_chanid,
            person.nature as person_nature')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert', 'cert'))
            ->order('person.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['person_chanid_name'] = DeptModel::get_name_by_pk($item['person_chanid']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $useList = [];
                $bidList = CertUseBidListModel::alias('list')
                    ->field('use.bidid,list.*')
                    ->leftJoin('cert_use_bid use', 'use.id = list.useid')
                    ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                    ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.certid' => $item['id']])
                    ->select()->toArray();
                foreach ($bidList as $vvv){
                    $engininfo = BidModel::where(['id'=>$vvv['bidid']])->find();
                    $useList[] = [
                        'engin_name' => $engininfo['name'],
                        'engin_chanid_name' => DeptModel::get_name_by_pk($engininfo['chanid']),
                        'business_name' => $engininfo['business'] == 1 ? '自营' : '联营',
                        'place' => $vvv['place'],
                        'issuo' => $vvv['issuo'],
                        'engin_state' => (new BidService())->get_bid_state_name_tag($engininfo)
                    ];
                }

                $enginList = CertUseListModel::alias('list')
                    ->field('use.enginid,list.*')
                    ->leftJoin('cert_use use', 'use.id = list.useid')
                    ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                    ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.certid' => $item['id']])
                    ->select()->toArray();
                foreach ($enginList as $vvv){
                    $engininfo = EnginModel::where(['id'=>$vvv['enginid']])->find();
                    $useList[] = [
                        'engin_name' => $engininfo['name'],
                        'engin_chanid_name' => DeptModel::get_name_by_pk($engininfo['chanid']),
                        'business_name' => $engininfo['business'] == 1 ? '自营' : '联营',
                        'place' => $vvv['place'],
                        'issuo' => $vvv['issuo'],
                        'engin_state' => (new EnginService())->get_engin_state_name_tag($engininfo['id'], $engininfo['state'])
                    ];
                }

                $item['useList'] = $useList;
                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }
    public function cert_count_shu(Request $request)
    {
        $person_nature = (new OptService())->get_base_info('person_nature');
        if($request->isPost()){
            $param = $request->post();
            get_page($param);

            $where[] = ['cert.deleted_user','=','0'];
            $where[] = ['cert.comid','=',$this->userinfo['comid']];
            $where[] = ['cert.state','not in', [2,3]];

            if(isset($param['chanid']) && !empty($param['chanid'])){
                $where[] = ['person.chanid','=',$param['chanid']];
            }
            if(isset($param['name']) && !empty($param['name'])){
                $where[] = ['cert.name','like', '%'.$param['name'].'%'];
            }

            $data['chanid'] = (new UserService())->get_chaninfo_all();
            $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

            $filedNames = '';
            foreach ($person_nature as $vvv){
                $filedNames .= ",COUNT(case when `person`.`nature`=".$vvv['value']." then `person`.`nature` END) AS nature".$vvv['value'];
            }

            $data['data'] = CertModel::alias('cert')
                ->field('cert.name,count(cert.name) as allnum'.$filedNames)
                ->leftjoin('cert_person person','person.id=cert.personid')
                ->where($where)
                ->where((new MenuService())->get_miss_where('cert', 'cert'))
                ->order('cert.id DESC')
                ->group('cert.name')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
            return outputJson(2000,lang('code_2000'),$data);
        }else{


            $data = [];
            $data[] = ['type' => 'checkbox', 'fixed' => 'left'];
            $data[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=> 'left'];
            $data[] = ['field' => 'name', 'title' => '证书名称'];
            $data[] = ['field' => 'allnum', 'title' => '证书数量(本)'];
            foreach ($person_nature as $item){
                $data[] = ['field' => 'nature'.$item['value'], 'title' => $item['title']];
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function cert_count_zhuan(Request $request)
    {
        $person_nature = (new OptService())->get_base_info('person_nature');
        if($request->isPost()){
            $param = $request->post();
            get_page($param);

            $where[] = ['cert.deleted_user','=','0'];
            $where[] = ['cert.comid','=',$this->userinfo['comid']];
            $where[] = ['cert.state','not in', [2,3]];

            if(isset($param['chanid']) && !empty($param['chanid'])){
                $where[] = ['person.chanid','=',$param['chanid']];
            }
            if(isset($param['name']) && !empty($param['name'])){
                $where[] = ['cert.name','like', '%'.$param['name'].'%'];
            }

            $data['chanid'] = (new UserService())->get_chaninfo_all();
            $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

            $filedNames = '';
            foreach ($person_nature as $vvv){
                $filedNames .= ",COUNT(case when `person`.`nature`=".$vvv['value']." then `person`.`nature` END) AS nature".$vvv['value'];
            }

            $list = CertModel::alias('cert')
                ->field(Db::raw("cert.name,substring_index( substring_index( cert.major, '[]', b.id), '[]', -1) AS major".$filedNames))
                ->leftjoin('cert_person person','person.id=cert.personid')
                ->leftJoin('help_topic b',Db::raw("b.id < ( length( cert.major ) - length( REPLACE ( cert.major, '[]', '' ) ) )/2+2"))
                ->where($where)
                ->where((new MenuService())->get_miss_where('cert', 'cert'))
                ->order("major ASC")
                ->group("major,name")
                ->select()->toArray();

            foreach ($list as &$item){
                $item['allnum'] = 0;
                foreach ($person_nature as $vvv){
                    $item['allnum'] += $item['nature'.$vvv['value']];
                }
            }


            $data['data'] = $list;
            return outputJson(2000,lang('code_2000'),$data);
        }else{

            $data = [];
            $data[] = ['type' => 'checkbox', 'fixed' => 'left'];
            $data[] = ['type' => 'numbers', 'title' => '序号', 'fixed'=> 'left'];
            $data[] = ['field' => 'name', 'title' => '证书名称'];
            $data[] = ['field' => 'major', 'title' => '证书专业'];
            $data[] = ['field' => 'allnum', 'title' => '数量(本)'];
            foreach ($person_nature as $item){
                $data[] = ['field' => 'nature'.$item['value'], 'title' => $item['title'].'(本)'];
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function cert_count_jian(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['cert.deleted_user','=','0'];
        $where[] = ['cert.comid','=',$this->userinfo['comid']];
        $where[] = ['cert.state','not in', [2,3]];
        $where[] = ['cert.name','like', '%建造师%'];

        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['person.chanid','=',$param['chanid']];
        }
        if(isset($param['person_name']) && !empty($param['person_name'])){
            $where[] = ['person.name','like', '%'.$param['person_name'].'%'];
        }
        if(isset($param['person_nature']) && !empty($param['person_nature'])){
            $where[] = ['person.nature','=',$param['person_nature']];
        }

        $data['chanid'] = (new UserService())->get_chaninfo_all();
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['nature'] = (new OptService())->get_base_info('person_nature');
        $data['is_nature'] = isset($param['nature']) ? $param['nature'] : '';

        $data['data'] = CertModel::alias('cert')
            ->field('cert.*,person.name as person_name,person.chanid as person_chanid,
            person.nature as person_nature')
            ->leftjoin('cert_person person','person.id=cert.personid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('cert', 'cert'))
            ->order('person.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['person_chanid_name'] = DeptModel::get_name_by_pk($item['person_chanid']);
                $item['person_nature'] = (new OptService())->get_base_showname('person_nature',$item['person_nature']);
                $item['major'] = '<div style="line-height: 20px">'.str_replace('[]','<br/>',$item['major']).'</div>';

                $expiry_dtArr = explode('[]',$item['expiry_dt']);
                $arr = [];
                foreach($expiry_dtArr as $v){
                    if(empty($v)){
                        $arr[] = $v;
                    }else{
                        if($v < date('Y-m-d')){
                            $arr[] = '<span style="color:red;">'.$v.'</span>';
                        }else{
                            $arr[] = $v;
                        }
                    }
                }
                $item['expiry_dt'] = '<div style="line-height: 20px">'.implode('<br/>',$arr).'</div>';
                $item['statueuse_name'] = (new CertService())->get_cert_statueuse_name($item['statueuse']);


                $useBid = [];
                $bidList = CertUseBidListModel::alias('list')
                    ->field('use.bidid,list.*')
                    ->leftJoin('cert_use_bid use', 'use.id = list.useid')
                    ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0,'list.opt' => 1])
                    ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.certid' => $item['id']])
                    ->select()->toArray();
                foreach ($bidList as $vvv){
                    $engininfo = BidModel::where(['id'=>$vvv['bidid']])->find();
                    if($engininfo['deleted_user'] == 0 && $engininfo['status'] == 1 && $engininfo['isqi'] == 0){
                        if($engininfo['state'] == 1 || $engininfo['state'] == 3){
                            $useBid[] = ['engin_name' => $engininfo['name'],];
                        }
                    }

                }
                $item['useBid'] = $useBid;

                $useEngin = [];
                $enginList = CertUseListModel::alias('list')
                    ->field('use.enginid,list.*')
                    ->leftJoin('cert_use use', 'use.id = list.useid')
                    ->where(['use.comid' => $this->userinfo['comid'], 'use.deleted_user' => 0])
                    ->where(['use.isturn' => 1, 'use.status' => 1, 'use.isreal' => 1, 'list.certid' => $item['id']])
                    ->select()->toArray();
                foreach ($enginList as $vvv){
                    $engininfo = EnginModel::where(['id'=>$vvv['enginid']])->find();
                    if($engininfo['deleted_user'] == 0 && $engininfo['status'] == 1){
                        if($engininfo['state'] == 0 || $engininfo['state'] == 3){
                            $useEngin[] = ['engin_name' => $engininfo['name'],];
                        }
                    }
                }
                $item['useEngin'] = $useEngin;


                $bbarr = [];
                $bblist = CertModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                    ->where('state','not in', [2,3])
                    ->where(['personid'=>$item['personid']])
                    ->where("name like '%B%' or name like '%b%'")
                    ->select()->toArray();
                foreach ($bblist as $vvv){
                    $expiry_dt_arr = explode('[]', $vvv['expiry_dt']);
                    $bbarr[] = [
                        'name' => $vvv['name'],
                        'expiry_dt' => isset($expiry_dt_arr[0]) ? $expiry_dt_arr[0] : '',
                    ];
                }
                $item['bbarr'] = $bbarr;


                $qiarr = [];
                $qilist = CertModel::where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                    ->where('state','not in', [2,3])
                    ->where(['personid'=>$item['personid']])
                    ->where("name not like '%B%' and name not like '%b%'")
                    ->where('id','neq', $item['id'])
                    ->select()->toArray();
                foreach ($qilist as $vvv){
                    $expiry_dt_arr = explode('[]', $vvv['expiry_dt']);
                    $qiarr[] = [
                        'name' => $vvv['name'],
                        'expiry_dt' => isset($expiry_dt_arr[0]) ? $expiry_dt_arr[0] : '',
                    ];
                }
                $item['qiarr'] = $qiarr;



                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }



}


















